RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.38% (6.14%*) • Home Loan Fixed: 5.44% (6.26%*) • Fixed: 5.44% (6.26%*) • Variable: 5.38% (6.14%*) • Investment IO: 5.69% (6.52%*) • Investment PI: 5.49% (5.98%*)

Show a Change.org Progress Bar with WordPress Shortcode

Show a Change.org Progress Bar with WordPress Shortcode

The WordPress shortcode (and PHP function) on this page will render a Change.org petition progress bar onto your WordPress post or page. As the count petition incrementally increases the color of the graph will change until it has reached its goal (100%) - at which time the graph will change to green.

Before the shortcode function will work, you must first register for an API Key here .

The Result

Using the sample petition here , the following will be rendered into your WordPress page or post (we have no affiliation with the campaign whatsoever... and yes, he was sacked).

Petition is now closed.

While the HTML generated in our example is quite minimal, quite a lot of information is returned by the API and stored locally in your own WordPress database (as a time-limited transient). Alter the reference to $num_words to return more text, and alter the actual HTML with the data referenced in the code.

Shortcode used was as follows: [change url="https://www.change.org/p/sack-salim-mehajer-and-auburn-council"].

An example of a campaign without text is as follows:

Petition is now closed.

Display Other Types of Data

To show a count only, use [changedata]. The result: 0. The same shortcode can be used to return other array values via an attribute. For example, [changedata type="percent"] returns NAN%, and [changedata type="created_at"] returns 1st January 1970.

The Shortcode

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin. You may optionally download and install our plugin from the bottom of of the page.

If you download the plugin, you'll find an option to update your API key in the Tools menu.

Show a Change.org Progress Bar with WordPress Shortcode

If plugin is installed, update the API key from Tools menu.

The first function retrieves the change data and stores it as a WordPress transient.

1
<?php 
2
/*
3
 Show a Change.org Progress Bar with WordPress Shortcode
4
 http://www.beliefmedia.com/change-graph-wordpress
5
*/
6
 
7
function beliefmedia_change_data($url, $apikey, $cache) {
8
 
9
  /* Get transient data */
10
  $transient = 'bmch_' . md5(serialize(func_get_args()));
11
  $response = get_transient($transient);
12
 
13
  if ($response !== false) {
14
    return (array) $response;
15
 
16
   } else {
17
 
18
     /* Query params */
19
     $parameters = array(
20
      'api_key' => $apikey,
21
      'petition_url' => $url
22
     );
23
 
24
     /* Query URL */
25
     $query_string = http_build_query($parameters);
26
     $requesturl = 'https://api.change.org/v1/petitions/get_id' . '?' . $query_string;
27
 
28
     /* Get data */
29
     $response = @file_get_contents($requesturl);
30
 
31
     /* Save response */
32
     if ($response !== false) {
33
 
34
        $json_response = json_decode($response, true);
35
        $petition_id = $json_response['petition_id'];
36
 
37
        /* Get signature count & other data */
38
        $parameters = array(
39
          'api_key' => $apikey,
40
          'petition_ids' => $petition_id
41
        );
42
 
43
        /* Build query for Change data */
44
        $query_string = http_build_query($parameters);
45
        $requesturl = 'https://api.change.org/v1/petitions' . '?' . $query_string;
46
 
47
        /* Get data */
48
        $response = @file_get_contents($requesturl);
49
 
50
           if ($response !== false) {
51
 
52
              $response = json_decode($response, true);
53
 
54
                if ($response !== false) {
55
 
56
                  /* Petition data from array */
57
                  $petition = $response['petitions'][0];
58
 
59
                  /* Save transient */
60
                  set_transient($transient, $petition, $cache);
61
 
62
               }
63
 
64
           }
65
 
66
       }
67
 
68
  /* Returns data array or false */
69
  return ($response !== false) ? (array) $petition : false;
70
 }
71
}

One you have the data, you can render it any manner of your choosing. The following will take the cached data and return a progress bar.

1
<?php 
2
/*
3
 Show a Change.org Progress Bar with WordPress Shortcode
4
 http://www.beliefmedia.com/change-graph-wordpress
5
*/
6
 
7
function beliefmedia_change_graph($atts) {
8
 
9
  $atts = shortcode_atts(array(
10
    'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
11
    'url' => 'https://api.change.org/p/auburn-city-council-the-hon-paul-toole-mp-local-government-minister-sacksalimmehajer',
12
    'width' => '450',
13
    'height' => '30',
14
    'data' => 1,
15
    'font' => 'font: normal 12px verdana', /* Text in progress bar */
16
    'cache' => 3600 * 12,
17
    'num_words' => '15',
18
  ), $atts);
19
 
20
  /* Get response array */
21
  $response = beliefmedia_change_data($atts['url'], $atts['apikey'], $atts['cache']);
22
 
23
   if ($response['title'] != '') $title = $result['title'];
24
   $percent = ($response['signature_count'] / $response['goal']) * 100;
25
   $target = ($percent >= 100) ? '100' : round($percent, 0);
26
 
27
   $url = $response['url'];
28
 
29
   /* Letter body */
30
   $letter_body = $response['letter_body'];
31
   $letter_body = wp_strip_all_tags($letter_body);
32
   $letter_body = wp_trim_words($letter_body, $num_words = $atts['num_words'], $more = null);
33
 
34
   $count =  $petition['signature_count'];
35
 
36
   /* Progress bar colors (until target) */
37
   switch ($percent) {
38
     case ($percent <= 50):
39
       $bgcolor = '#CCCCCC';
40
       break;
41
     case ( ($percent > 50) && ($percent <= 80) ):
42
       $bgcolor = '#D12C2C';
43
       break;
44
     case ( ($percent > 80) && ($percent < 100) ):
45
       $bgcolor = '#FF9F40';
46
       break;
47
     case ($percent >= 100):
48
       $bgcolor = '#006A35';
49
      break;
50
   }
51
 
52
   /* Build prorgess bar */
53
   if ($atts['data']) $result .= '<div style="max-width: ' . $atts['width'] . 'px; margin: auto; text-align: left;"><a href="' . $url . '" target="_blank" rel="noopener noreferrer"><strong>Sign our petition on Change</a></strong>: ' . $letter_body . '</div>';
54
   $result .= '<div style="border: 1px solid black; max-width: ' . $atts['width'] . 'px; height: ' . $atts['height'] . 'px; background: #cccccc; ' . $atts['font'] . '; position: relative; margin: auto; margin: 10px auto;">
55
<div style="width: ' . $percent . '%; background: ' . $bgcolor . '; color: #ffffff; text-align: left; height: ' . $atts['height'] . 'px; vertical-align: middle; line-height:' . $atts['height'] . 'px;"><span style="display: inline-block; position: absolute; width: 100%; left: 0; margin-left: 12px;">Currently ' . number_format($response['signature_count']) . ' of ' . number_format($response['goal']) . ' signatures (' . round($percent, 1) . '%)</span></div>
56
</div>';
57
 
58
 return $result;
59
}
60
add_shortcode('change', 'beliefmedia_change_graph');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

The following attributes apply to the first function.

apikey

Before the shortcode function will work, you must first register for an API Key here . It should be added to the shortcode function.

url

The URL is the URL of the petition page you with to reference. In our case, we've used this page for our example.

width

The width of the percentage graph.

height

The height of the percentage graph.

data

By default a short description will show (with a link). To disable, use data="0".

font

The full font style you wish to use for text in the percentage graph. Default: font: normal 12px verdana.

cache

Cache determines the amount of time the result will be stored locally in your WordPress database. If it's a slow-moving petition, perhaps consider updating the result only a couple of times a day to minimise the number of requests make to the Change API (cache="3600 * 12).

num_words

The number of words to return in the description text.

Return Data Types

The second function returns specific data from the array returned by the Change API.

1
<?php 
2
/*
3
 Return specific Change.org data
4
 Show a Change.org Progress Bar with WordPress Shortcode
5
 http://www.beliefmedia.com/change-graph-wordpress
6
 petition_id, title, status, url, overview, targets, letter_body, signature_count, image_url, category, goal, created_at, end_at, creator_name, creator_url, organization_name, organization_url.
7
*/
8
 
9
function beliefmedia_change_datas($atts) {
10
 
11
  $atts = shortcode_atts(array(
12
    'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
13
    'url' => 'https://api.change.org/p/auburn-city-council-the-hon-paul-toole-mp-local-government-minister-sacksalimmehajer',
14
    'type' => 'signature_count',
15
    'cache' => 3600 * 12,
16
    'num_words' => '15',
17
    'format' => 'jS F Y' /* Time */
18
  ), $atts);
19
 
20
  /* Get response array */
21
  $response = beliefmedia_change_data($atts['url'], $atts['apikey'], $atts['cache']);
22
 
23
  /* Apply number format to the following */
24
  $count_array = array('signature_count', 'goal');
25
  $data_array = array('petition_id', 'title', 'status', 'url', 'overview', 'targets', 'letter_body', 'signature_count', 'image_url', 'category', 'goal', 'created_at', 'end_at', 'creator_name', 'creator_url', 'organization_name', 'organization_url', 'percent');
26
  $date_array = array('created_at', 'end_at');
27
 
28
  if ( ($response !== false) && (in_array($atts['type'], $data_array)) ) {
29
 
30
        switch ($atts['type']) {
31
 
32
            case 'percent':
33
                $percent = round(($response['signature_count'] / $response['goal']) * 100);
34
                return $percent;
35
                break;
36
 
37
            case 'letter_body':
38
                /* Letter body */
39
                $letter_body = $response['letter_body'];
40
                $letter_body = wp_strip_all_tags($letter_body);
41
                $letter_body = wp_trim_words($letter_body, $num_words = $atts['num_words'], $more = null);
42
                return $letter_body;
43
                break;
44
 
45
            case (in_array($atts['type'], $count_array)):
46
                $key = $atts['type'];
47
                return number_format( (float) $response["$key"], 0);
48
                break;
49
 
50
            case (in_array($atts['type'], $date_array)):
51
                $key = $atts['type'];
52
                return date($atts['format'], strtotime($response["$key"]));
53
                break;
54
 
55
            default:
56
                $key = $atts['type'];
57
                return $response["$key"];
58
 
59
        }
60
 
61
  } else {
62
 
63
    return '<strong>Invalid</strong>';
64
 
65
 }
66
}
67
add_shortcode('changedata', 'beliefmedia_change_datas');

Date Type Attributes

apikey

Before the shortcode function will work, you must first register for an API Key here . It should be added to the shortcode function.

url

The URL is the URL of the petition page you with to reference. In our case, we've used this page for our example.

type

The type is any of the following: petition_id, title, status, url, overview, targets, letter_body, signature_count, image_url, category, goal, created_at, end_at, creator_name, creator_url, organization_name, organization_url, or percent. Numbers are returned in a number format, and dates are formatted according to the format attribute below.

cache

Cache determines the amount of time the result will be stored locally in your WordPress database. If it's a slow-moving petition, perhaps consider updating the result only a couple of times a day to minimise the number of requests make to the Change API (cache="3600 * 12). Try and keep it the same as the first function to avoid caching two responses of the same data.

num_words

If a letter_body attribute is used, it will be truncate to num_words.

format

If a created_at or end_at attribute is used, it will be formatted with the PHP date() function. Default is jS F Y.

PHP Function

A PHP function to be used outside of WordPress is included below. Usage requires Simple Cache.

Considerations

  • While we've used a fairly crude CSS div for rendering the percentage graph, it's often more effective to use Google charts or any of the other open source graphing applications written for PHP applications.
  • The incremental colors used in the progress bar can be altered by altering the $bgcolor variable. Additionally, the percentage at which the bar changes color can be altered in the same block of code.

Download


Title: Show a Change.org Progress Bar in WordPress (Plugin)
Description: Show a Change.org Progress Bar with WordPress Shortcode or PHP.
  Download • Version 0.2, 4.2K, zip, Category: WordPress Plugins (General)
WordPress Shortcodes, (2.2K)    PHP Code & Snippets, (2.3K)    

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment