Back to Top

Add Polldaddy Polls to WordPress

Previous Post:

Add Polldaddy Polls to WordPress

Having polls in your posts or your sidebars might attract your visitors’ interest in one way or another. The question is what poll systems you can use and how you should use them. There are some WordPress plugins out there that do their jobs just fine, but if you want a more comprehensive solution, Polldaddy will be your perfect poll system.

Adding Polldaddy.com’s polls to your blog is rather easy, but all the default configurations and the codes you use to show the polls on your blog can actually be customized further and better than you can imagine. After registering for a free (or paid) account here you can start choosing one of the two options below to utilize Polldaddy on your blog.

Using a Polldaddy WordPress plugin

Undoubtedly this would be the option for many WordPress users out there who wants a simple and hassle-free approach. The plugin I am talking about is no other than PollDaddy Polls & Ratings, an extremely popular plugin in the plugin directory.

PollDaddy Polls & Ratings will work just like another Polldaddy’s administration page and you will find it very similar if you have ever actually logged in to http://polldaddy.com.

Polldaddy Polls & Ratings

Polldaddy Polls & Ratings

This plugin allows you to create new polls or edit existing polls that you have created on polldaddy.com. You can also define custom styles or customize a pre-defined styles using a very advanced and intuitive interface with almost no page reloading needed. With the latest version of this plugin, however, I don’t see an option to apply CSS rules directly to your custom styles (please correct me if I am wrong).

Another cool feature this plugin offers is the ability to separate your blog’s polls and your account’s poll, which is very useful for blogs that have several users that can access the back-end system. If you have, for example, an author on your blog then he will be able to create his own blog polls which can be administrated by you while having his account (or private) polls administrated by no one but him, very convenient I must say.

Now it looks like I am telling you to just use this plugin and forget about the rest of this article (I mean the fun part?) To say the truth, I do not recommend that you use this plugin at all, and the reason?

First of all, do you really need all those fancy admin pages like that if you can do exactly the same and even more on polldaddy.com? Of course you can benefit from account and blog poll separation, but what if you’re the only author of the blog or you simply do not want other users to create polls?

The second problem with this plugin is it doesn’t come with just poll, it also comes with rating and therefore is rather heavier than needed (and you might find yourself in trouble with the memory usage limit before you know it: http://wordpress.org/support/topic/plugin-polldaddy-pol ... y-messages).

Finally, with more than 6000 lines of codes that focus on administration and other things, this plugin completely lacks the ability to show latest polls or random polls, which would be a major turn-off if you ask me.

Now if you are still interested in this plugin, please go ahead and try it. Otherwise, take a deep breath and try the not-so-simple way to add Polldaddy polls to your blog.

Using your own codes

IMPORTANT: Codes in this section is now obsolete and is kept for reference only. Download the official plugin here: BWP Polldaddy.

Normally when you log in to your account on polldaddy.com, and then add polls using the admin pages, you will have the option to embed your polls on a wide variety of systems. Since we are using a self-hosted WordPress installation and you don’t use a plugin at all you would need, for example, copy these codes to your theme files:

<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/4563570.js"></script>
<noscript>
	<a href="http://polldaddy.com/poll/4563570/">Just a test question</a><span style="font-size:9px;"><a href="http://polldaddy.com/features-surveys/">online surveys</a></span>
</noscript>

Notice the number that is referenced 2 times? That’s the ID of our example poll and we are going to use it again later on (you might use your own ID if you wish).

Also notice this part: <span style="font-size:9px;"><a href="http://polldaddy.com/features-surveys/">online surveys</a></span> in the <noscript>1 tag, it is completely optional and in my opinion you should remove it, there is no real use for that link anyway.

Adding polls to your post contents or sidebar can be that easy: a simple copy and paste, but what if you have more than one polls and you want to automatically display the latest polls in some kinds of orders or randomly display just one poll?

The simplest thing to do is to create an array of all poll IDs you have and then loop through them to output your polls, like so:

<?php
$my_polldaddy = array(4563570, 4563571, 4563572); // polls will appear in the same order

foreach ($my_polldaddy as $poll)
{
?>
	<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/<?php echo $poll; ?>.js"></script>
	<noscript>
		<a href="http://polldaddy.com/poll/<?php echo $poll; ?>/">View this poll without Javascript</a>
	</noscript>
<?php
}
?>

This snippet will basically output three polls on your blog and they are ordered the same way you put those IDs in the array.

If you want a random order, you can do it like this:

$my_polldaddy = array(4563570, 4563571, 4563572);

shuffle($my_polldaddy); // a PHP function to randomize an array2

The limitation of this approach is rather obvious: you have to keep track of all the poll IDs and you can’t have new polls added automatically to your array. Another problem you might have noticed is we have to replace the polls’ questions with a general phrase ‘View this poll without Javascript’ in the <noscript> tag. Of course you can add those questions as array keys in $my_polldaddy, but that is just too time-consuming, right?

In fact, there’s a better approach: using Polldaddy API3.

Using Polldaddy API

This section is rather advanced so reader discretion is advised (I mean it =P). Also note that you must have PHP 5.2.0 or higher for this approach to work. For users of older PHP versions please comment so I may have a patch.

The first thing you will probably have to do is get a Polldaddy API key, which is available for free here: http://polldaddy.com/register/. You will need a Polldaddy account for that (at this point you might have one already). The partner name is also required but you can just input anything you want, e.g. MyPollApp.

After the API key has been generated, copy and keep it in a safe place :).

The next step will require some coding and for the sake of simplicity you can just use functions.php to type all the codes if you wish. It is suggested that, however, you create a new file named polldaddy.php and put it in your theme directory (preferably in a sub-folder named ‘includes’).

For the rest of this article I will use polldaddy.php as the file containing all the needed codes if you don’t mind.

Now copy all the codes below and paste them into polldaddy.php:

<?php
/**
 * Copyright (c) 2011 Khang Minh <betterwp.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

function bwp_get_poll($id = '')
{
	global $bwp_polldaddy;

	$polls = $bwp_polldaddy->get_cached_polls();

	if (!empty($id) && isset($polls) && is_array($polls))
	{
		foreach ($polls as $poll)
		{
			if ($id == $poll->id)
				return $poll;
		}
	}

	return '';
}

function bwp_get_polls($limit = 0, $orderby = '', $order = 'desc')
{
	global $bwp_polldaddy;

	$polls = $bwp_polldaddy->get_cached_polls();

	if (!isset($polls) || !is_array($polls)) return array();

	// Sort by rand
	if ('rand' == $orderby)
	{
		shuffle($polls);
		return (!empty($limit)) ? array_slice($polls, 0, $limit) : $polls;
	}

	// Begin sorting
	$orderby = (empty($orderby) || !in_array($orderby, array('created', 'responses'))) ? 'id' : $orderby;
	$sorted_polls = array();
	foreach ($polls as $poll)
	{
		$sorted_polls[$poll->{$orderby}] = $poll;
	}
	if ('asc' == $order)
		ksort($sorted_polls);
	else
		krsort($sorted_polls);

	// Limit result
	return (!empty($limit)) ? array_slice($sorted_polls, 0, $limit) : $sorted_polls;
}

class BWP_PollDaddy {

	var $api_key;
	var $api_host = 'http://api.polldaddy.com/';
	var $user_code;
	var $is_ssl;
	var $polls;
	var $last_updated;

	function __construct($api_key, $cache_time = 43200, $is_ssl = false)
	{
		$this->api_key = (!empty($api_key)) ? $api_key : NULL;
		$this->is_ssl = (true == $is_ssl) ? true : false;
		$this->api_host = (true == $this->is_ssl) ? 'https://api.polldaddy.com/' : $this->api_host;
		// Get data
		$this->user_code = get_option('bwp_polldaddy_usercode');
		$this->polls = get_option('bwp_polldaddy_polls');
		$this->last_updated = get_option('bwp_polldaddy_updated');
		// Get all data again if the cache is expired or not found
		// Admin only
		if (is_user_logged_in() && current_user_can('manage_options'))
		{
			$time = time();
			if (empty($this->last_updated) || (!empty($cache_time) && $this->last_updated + $cache_time <= $time))
			{
				// not really have to update this
				$this->user_code = $this->get_usercode();
				if (!empty($this->user_code))
				{
					$this->polls = $this->get_polls();
					$this->last_updated = $time;
				}
			}
			else
			{
				$this->user_code = (!$this->user_code) ? $this->get_usercode() : $this->user_code;
				$this->polls = (!$this->polls || !is_array($this->polls)) ? $this->get_polls() : $this->polls;
			}
			// Update all data
			update_option('bwp_polldaddy_usercode', $this->user_code);
			update_option('bwp_polldaddy_polls', $this->polls);
			update_option('bwp_polldaddy_updated', $this->last_updated);
		}
	}

	function do_request($request)
	{
		if (empty($request)) return '';

		$response = ''; $result = '';

		if (function_exists('wp_remote_post'))
		{
			$response = wp_remote_post(
				$this->api_host,
				array(
					'headers' => array('Content-Type' => 'application/json; charset=utf-8', 'Content-Length' => strlen($request)),
					'user-agent' => 'PollDaddy PHP Client/1.0',
					'body' => $request
				)
			);

			if (!$response || is_wp_error($response))
				return '<strong>Polldaddy Error:</strong> Could not connect to API host or no data found';

			$result = wp_remote_retrieve_body($response);
		}
		else
		{
			/* Borrowed from the PollDaddy Polls & Rating Plugin */
			$parsed = parse_url($this->api_host);
			if (!isset($parsed['host']) && !isset($parsed['scheme']))
				return 'Bad API host';

			$fp = fsockopen(
				$parsed['host'],
				true == $this->is_ssl ? 443 : 80,
				$err_num,
				$err_str,
				3
			);						

			if (!$fp)
				return '<strong>Polldaddy Error:</strong> Could not connect to API host';

			if (function_exists('stream_set_timeout'))
				stream_set_timeout($fp, 3);

			if (!isset($parsed['path']) || !$path = $parsed['path'] . (isset($parsed['query']) ? '?' . $parsed['query'] : ''))
				$path = '/';

			$header  = "POST $path HTTP/1.0\r\n";
			$header .= "Host: {$parsed['host']}\r\n";
			$header .= "User-agent: PollDaddy PHP Client/1.0\r\n";
			$header .= "Content-Type: application/json; charset=utf-8\r\n";
			$header .= 'Content-Length: ' . strlen($request) . "\r\n";

			fwrite($fp, "$header\r\n$request");

			$response = '';
			while (!feof($fp))
				$response .= fread($fp, 4096);
			fclose($fp);

			if (!$response)
				return '<strong>Polldaddy Error:</strong> Could not connect to API host or no data found';

			list($headers, $result) = explode("\r\n\r\n", $response, 2);
		}

		return json_decode($result);
	}

	function get_cached_polls()
	{
		return $this->polls;
	}

	function get_polls()
	{
		if (empty($this->user_code))
			return '';

		$request = '
			{"pdRequest": {
				"partnerGUID": "' . $this->api_key . '",
				"userCode": "' . $this->user_code . '",
				"demands": {
					"demand": {
							"id": "GetPolls"
						}
					}
				}
			}
		';

		$response = $this->do_request($request);

		if (!isset($response->pdResponse->demands->demand[0]->polls->poll))
			return '<strong>Polldaddy Error:</strong> There was a problem getting polls.';

		return $response->pdResponse->demands->demand[0]->polls->poll;
	}

	function get_usercode()
	{
		if (!isset($this->api_key))
			return '';

		$request  = '
			{"pdAccess": {
			    	"partnerGUID": "' . $this->api_key . '",
					"partnerUserID": "0",
					"demands": {
						"demand": {
							"id": "GetUserCode"
						}
					}
				}
			}
		';

		$response = $this->do_request($request);

		if (!isset($response->pdResponse->userCode))
			return '<strong>Polldaddy Error:</strong> Account inaccessible, please recheck your API key.';

		return $response->pdResponse->userCode;
	}
}
?>

and then add this to your theme’s functions.php:

// remove 'includes/' if you use no sub-folder
include_once('includes/polldaddy.php');
// init Polldaddy
$bwp_polldaddy = new BWP_PollDaddy('insert your API key here');

Now if you refresh any page the class will try to connect to polldaddy.com to get the needed data (only if you log in as an admin).

The process will take about one to two seconds to complete and after that the data will be cached for a period of time (by default it is cached for 12 hours, measured in seconds). You can change the default cache time by doing this:

// init Polldaddy
// cache data for 1 day (86400 seconds)
$bwp_polldaddy = new BWP_PollDaddy('insert your API key here', 86400);

If you rarely update your polls, you can set the cache time to zero to prevent the class from trying to refresh the data. When you do edit a poll, simply change the time to a very small number to update the polls immediately.

If you have also purchased a paid account on polldaddy.com you might also enable SSL for Polldaddy, like so:

// init Polldaddy
$bwp_polldaddy = new BWP_PollDaddy('insert your API key here', 43200, true);

Now to show a specific poll on your blog you will add this snippet to your theme files (in this example we use the same ID used above):

<?php
// we get all the poll data
// which means we can show the question in the <noscript> tag now =)
$poll = bwp_get_poll('4563570');
?>
	<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/<?php echo $poll->id; ?>.js"></script>
	<noscript>
		<a href="http://polldaddy.com/poll/<?php echo $poll->id; ?>/"><?php echo $poll->content; ?></a>
	</noscript>

To show all recent polls ordered descendingly by date of creation, do this instead:

<?php
// by default polls are sorted descendingly ('desc' or empty) by their IDs. To sort ascendingly, use 'asc'.
// sorting by ID is actually equivalent to sorting by 'created'
// the number '0' means 'no limit'
$polldaddy_polls = bwp_get_polls(0, 'created', 'desc');
foreach ($polldaddy_polls as $poll)
{
?>
	<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/<?php echo $poll->id; ?>.js"></script>
	<noscript>
		<a href="http://polldaddy.com/poll/<?php echo $poll->id; ?>/"><?php echo $poll->content; ?></a>
	</noscript>
<?php
}
?>

Now if you want to show just one latest poll, simply change the 5th line in the above snippet to this:

$polldaddy_polls = bwp_get_polls(1);

and if you want to randomly show just one poll, use this:

/**
 * to order by the number of responses, change 'rand' to 'responses' (notice the 's').
 */
$polldaddy_polls = bwp_get_polls(1, 'rand');

If you need a shortcode to display polls in your post, you can create one easily using add_shortcode()4. The shortcode callback function should use the same functions above.

That’s it, enjoy this article! If you have any feedback or suggestion please feel free to comment!

References

  1. http://www.w3schools.com/TAGS/tag_noscript.asp []
  2. http://php.net/manual/en/function.shuffle.php []
  3. http://en.wikipedia.org/wiki/Application_programming_in ... _interface []
  4. http://codex.wordpress.org/Function_Reference/add_short ... _shortcode []

Take Social Sharing to
the Next Level with Monarch!

Take Social Sharing to the Next Level with Monarch!
Print Article Trackback Trackback to this Article   Subscribe to Comments RSS Subscribe to Comments RSS

13 Opinions for Add Polldaddy Polls to WordPress

  1. User's Gravatar
    1
    Umbada:D April 10, 2011 at 10:01 pm – Permalink

    Thanks for the class, although I chose to use your plugin, it rocks :D. I have a question, though. My API request to Polldaddy is very fast, less than 0.3s I think, is there any problem if I set the update interval to something small (I update polls often ya know)?

    • User's Gravatar
      2
      OddOneOut April 11, 2011 at 2:32 pm – Permalink

      Hi Umbada?

      It looks like your server is close to Polldaddy’s, that’s why it’s so fast! In that case there would be no problem of course, unless there’s a problem with Polldaddy’s server. And even if the request is slow, it will only slow the admin down, right? Glad you like it ;).

  2. User's Gravatar
    3
    Gh0st April 13, 2011 at 6:14 pm – Permalink

    Thank you for posting this up, I have a blog and I am trying to get only the ratings feature for each post. Tried your api step till “Now to show a specific poll on your blog you will add this snippet to your theme files (in this example we use the same ID above):”

    Where do I have to do that?

    Thanks.

    • User's Gravatar
      4
      OddOneOut April 13, 2011 at 6:23 pm – Permalink

      Hi Gh0st!

      This article is about adding polls not ratings to your posts, so you will have to modify the Polldaddy class I posted up there a little bit, have you done that yet?

      Where do I have to do that?

      In your theme files, at the place where you want to show the ratings, could be single.php or page.php. Or you might place it inside a rating.php and include it from those two files so next time you will only have to edit rating.php, a time-saver you know ;).

  3. User's Gravatar
    5
    Pallavi July 6, 2011 at 2:01 am – Permalink

    Hello,

    Thank you for the class. Its wonderful 🙂
    But I have some doubts. In function __construct, u have called 2 functions named, get_option & update_option. Where they are defined? I could not find them. For now, I have commented those lines. What exactly these functions do?

    • User's Gravatar
      6
      OddOneOut July 6, 2011 at 12:55 pm – Permalink

      Hi Pallavi!

      get_option and update_option are two WordPress’s core functions, located in wp-includes/functions.php. They are used to store some data (update_option), and get them (get_option) so you can use them where you need.

      As you can see, in the class, those functions are used to store and get the user_code (used to authenticate your request), the polls themselves (all polls in your account) as well as the last time you updated the polls. Nothing mysterious actually ;).

      • User's Gravatar
        7
        Pallavi July 6, 2011 at 8:27 pm – Permalink

        Hi,

        First of all thank you for your reply. I dont have any info about wordpress. I am writing Php code & want to use this class so was concerned about these 2 functions.
        Anyways, I have commented those lines & is using other part.

        • User's Gravatar
          8
          OddOneOut July 6, 2011 at 9:36 pm – Permalink

          That’s what I guessed too, but if you want to use this class without WordPress, you will have to modify some parts, especially those get and update option things, to make it work.

          Just ask if you have any question ;).

  4. User's Gravatar
    9
    Mike September 21, 2011 at 4:26 am – Permalink

    Hi there. Thanks for the tips. I can display the polls on my wordpress page but I want to display the results of each poll on a page or sidebar widget. Any suggestions? I do have an api key also.

    • User's Gravatar
      10
      OddOneOut September 22, 2011 at 9:19 pm – Permalink

      Hi Mike,

      What do you mean by ‘display the results’? You don’t want to let your visitors vote on a page and sidebar?

  5. User's Gravatar
    11
    Mike September 22, 2011 at 9:34 pm – Permalink

    In poll daddy, I built out two polls, Now, in my membership site, depending upon which gender logs in, will serve up the appropriate poll.

    Because neither gender will see the other’s poll, I want to display the results of both polls when either gender logs in.

  6. User's Gravatar
    12
    Christian T September 23, 2011 at 7:22 pm – Permalink

    Hi and thanks for this detailed post. Is this a lot better than using wp polls? I have a feeling that the latter has security holes in it and am very paranoid about WP plugins in general right now.

    • User's Gravatar
      13
      OddOneOut September 24, 2011 at 5:47 pm – Permalink

      Yes, WP Polls did have security holes, but I’m not sure if they have been fixed or not. I’d go with Polldaddy for sure as they have a strong team supporting it :).

Speak Up Your Mind!

An asterisk (*) indicates a required field and must be filled.




  • Web page and e-mail addresses turn into links automatically.
  • Wrap codes in: <code lang=""></code> or <pre lang="" extra="">
  • Lines and paragraphs break automatically.

Next Post: