Create a Voting Plugin for WordPress

44

WordPress, as a platform, has moved from only being a blogging platform, to a platform for a wide variety of websites. One major reason for this, is how easily WordPress can be customized and extended. This enables programmers to create far more functional sites than a normal blog. In the following tutorial we are going to create a plugin which will make wordpress an article voting site and also create a widget to display the top voted posts.

Creating the Plugin

To create a plugin create a file voteme.php in your wp-content/plugins/voteme folder. To create a plugin we have to add the plugin header as follows

<?php
/*
Plugin Name: Vote Me
Plugin URI:
Description: This plugin to add vote in posts
Author: Abbas
Version: 0.1
Author URI:
*/

We will also define some named constants for our plugin base url, and the plugin path as follows:

define('VOTEMESURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) );
define('VOTEMEPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );

Also, create a js folder in your voteme folder, and add a file voteme.js file in it.

The folder structure of the plugin would be as follows.

We will now enqueue the scripts by with ‘wp_enqueue_scripts’ and enqueue our JS file, and localize it to store the WP Ajax url which we will use for our ajax calls.

function voteme_enqueuescripts()
{
	wp_enqueue_script('voteme', VOTEMESURL.'/js/voteme.js', array('jquery'));
	wp_localize_script( 'voteme', 'votemeajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', voteme_enqueuescripts);</pre>

After this we should be able to see our plugin in the plugin list and we should activate it.

2

Adding the vote link to posts

Now we will add a link to all the posts displaying the current votes and a link to add the vote by ajax.
Following is the code

function voteme_getvotelink()
{
$votemelink = "";

$post_ID = get_the_ID();
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';

$link = $votemecount.' <a onclick="votemeaddvote('.$post_ID.');">'.'Vote'.'</a>';

$votemelink = '<div id="voteme-'.$post_ID.'">';
$votemelink .= '<span>'.$link.'</span>';
$votemelink .= '</div>';

return $votemelink;
}

function voteme_printvotelink($content)
{
return $content.voteme_getvotelink();
}
add_filter('the_content', voteme_printvotelink);

Here, we create a function voteme_getvote link which first gets the current post id and then reads the post meta_votemecount using get_post_meta. We use the post meta _votemecount to store the votes for a particular post. Then we create a link by adding the JavaScript function votemeaddvote on the click of the link. The function votemeaddvotewe will see shortly.

Next, we use the WordPress filter the_content to hook our function to add this link after each post. You will be able to see the number of votes and vote link below each post now.

3

Adding votes using Ajax

As we have added the vote link to every posts its time we make it functional to actually add votes. The JavaScript function which does the AJAX vote posting is below

function votemeaddvote(postId)
{
	jQuery.ajax({
	type: 'POST',
	url: votemeajax.ajaxurl,
	data: {
	action: 'voteme_addvote',
	postid: postId
},

success:function(data, textStatus, XMLHttpRequest){

	var linkid = '#voteme-' + postId;
	jQuery(linkid).html('');
	jQuery(linkid).append(data);
	},
	error: function(MLHttpRequest, textStatus, errorThrown){
		alert(errorThrown);
		}
	});
}

This sends an AJAX request to WordPress, and sends the action as voteme_addvote and the post ID. If the AJAX call is successful it just adds the data in the div for that post. If there is an error it will just display the error.

To handle the AJAX request we will have to create a function as follows

function voteme_addvote()
{
		$results = '';
		global $wpdb;
		$post_ID = $_POST['postid'];
		$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
		$votemecountNew = $votemecount + 1;
		update_post_meta($post_ID, '_votemecount', $votemecountNew);

		$results.='<div class="votescore" >'.$votemecountNew.'</div>';

		// Return the String
		die($results);
	}

		// creating Ajax call for WordPress
		add_action( 'wp_ajax_nopriv_voteme_addvote', 'voteme_addvote' );
		add_action( 'wp_ajax_voteme_addvote', 'voteme_addvote' );

In function voteme_addvote we get the post ID from the posted data and then get the current vote count for that post. Then we increment the vote by 1 and update the post meta again. Then we create a div with the new vote details and sent that back by using die($results);

To register this function to handle AJAX request for action: ‘voteme_addvote’ using the following wordpress hooks

// creating Ajax call for WordPress
		add_action( 'wp_ajax_nopriv_voteme_addvote', 'voteme_addvote' );
		add_action( 'wp_ajax_voteme_addvote', 'voteme_addvote' );</pre>

Now we’ll be able to click the vote link to add the vote on the post with AJAX.

4

Customizing WordPress admin to show post votes

It would be very convenient for the admin to be able to see the votes on the post edit page. Then from there he would be able to see the post details, and also the vote details on that page.

To add the vote details we need to add a hook on the filter ‘manage_edit-post_columns’ to add the Votes as a column on the post edit page as follows.

add_filter( 'manage_edit-post_columns', 'voteme_extra_post_columns' );
function voteme_extra_post_columns( $columns ) {
$columns[ 'votemecount' ] = __( 'Votes' );
return $columns;
}

Now we need to provide the value to display for this column. To do this we need to hook into the filtermanage_posts_custom_column. When we hook into this filter our function voteme_post_column_row is called and with the post column name. Here we only process out column votemecount and give the value for it. We read the value from our custom column _votemecount and echo it. The complete code for this is as follows.

function voteme_post_column_row( $column ) {
	if ( $column != 'votemecount' )
	return;

	global $post;
	$post_id = $post->ID;
	$votemecount = get_post_meta($post_id, '_votemecount', true) != '' ? get_post_meta($post_id, '_votemecount', true) : '0';
	echo $votemecount;

}

add_action( 'manage_posts_custom_column', 'voteme_post_column_row', 10, 2 );

On the post edit page you should be able to see the vote details column.

5

Sorting post on basics of votes in WordPress admin

It would be convenient for the admin if we make the vote column sortable. He would be able to see the most voted posts and also the least voted posts. To do this first we must make the Vote column clickable for sorting. To do this we hook into the filter manage_edit-post_sortable_columns and add the vote column to it as follows.

add_filter( 'manage_edit-post_sortable_columns', 'voteme_post_sortable_columns' );

function voteme_post_sortable_columns( $columns )
{
	$columns[ 'votemecount' ] = votemecount;
	return $columns;
}

Then we add a hook onto the load-edit.php hook when we have the order by request for votemecount we merge the sort parameters with

'meta_key' => '_votemecount',
'orderby' => 'meta_value_num'

So that it sorts on the basics of custom column and considers that column as numeric rather than as a string. The code for it is as follows.

add_action( 'load-edit.php', 'voteme_post_edit' );

function voteme_post_edit()
{
	add_filter( 'request', 'voteme_sort_posts' );
}
	function voteme_sort_posts( $vars )
{
	if ( isset( $vars['post_type'] ) &amp;&amp; 'post' == $vars['post_type'] )
	{
		if ( isset( $vars['orderby'] ) &amp;&amp; 'votemecount' == $vars['orderby'] )
		{
			$vars = array_merge(
			$vars,
			array(
			'meta_key' => '_votemecount',
			'orderby' => 'meta_value_num'
			)
			);
		}
	}
return $vars;
}

Now in the admin page the vote column will be clickable and clicking on it will sort the post on the basics of votes.

6

Allowing only Registered users to vote

We might want that not anyone can vote on the post. We might want to check that only users who are registered on our site will be able to vote. We’ll control this via creating a setting page for our plugin as follows

// Settings

add_action('admin_menu', 'voteme_create_menu');

function voteme_create_menu() {
add_submenu_page('options-general.php','Vote Me','Vote Me','manage_options', __FILE__.'voteme_settings_page','voteme_settings_page');
}
function voteme_settings_page() {
?>

<div class="wrap">

<?php
global $blog_id;

if( isset( $_POST['votemeoptionssubmit'] ) )
{
update_option( 'votemelogincompulsory' , $_POST[ 'votemelogincompulsory' ] );
}

?>
<div id="settingsform">
<form id='votemesettingform' method="post" action="">

<h1><?php echo 'Vote Me Settings'; ?></h1>

<Input type = 'Radio' Name ='votemelogincompulsory' value= 'yes' <?php if( get_option('votemelogincompulsory') == 'yes' ) echo 'checked';?> >User Must be logged in for voting
<br/>
<Input type = 'Radio' Name ='votemelogincompulsory' value= 'no' <?php if( get_option('votemelogincompulsory') != 'yes' ) echo 'checked';?> >User might not be logged in for voting
<br/><br/>
<p class="submit">
<input type="submit" id="votemeoptionssubmit" name="votemeoptionssubmit" class="button-primary" value="<?php echo 'Save'; ?>" />
</p>

</form>

</div>

</div>
<?php }

Here we hook onto admin_menu and create our setting page to show radio buttons for whether to allow voting for registered users only. Then based on the option selected by the admin we update the option votemelogincompulsory. The settings page will look as follows.

7

Then, update the voteme_getvotelink function to read the option votemelogincompulsory and to show the votelink or the login link depending on the option selected by the user and wthere the user is logged in or no. The code for it is as follows

function voteme_getvotelink()
{
	$votemelink = "";
	if( get_option('votemelogincompulsory') != 'yes' || is_user_logged_in() )
	{
		$post_ID = get_the_ID();
		$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';

		$link = $votemecount.' <a onclick="votemeaddvote('.$post_ID.');">'.'Vote'.'</a>';

		$votemelink = '<div id="voteme-'.$post_ID.'">';
		$votemelink .= '<span>'.$link.'</span>';
		$votemelink .= '</div>';
	}
else
{
	$register_link = site_url('wp-login.php', 'login') ;
	$votemelink = '<div class="votelink" >'." <a href=".$register_link.">"."Vote"."</a>".'</div>';
}

return $votemelink;
}

Creating a widget to display Top voted posts.

Now we will create a widget to display the top voted posts. First we create a function calledvoteme_get_highest_voted_posts which takes the number of posts and then displays those many post in order of the highest voted posts. It also displays the number of vote for each post.

function voteme_get_highest_voted_posts($numberofpost)
{
	$output = '';
	$the_query = new WP_Query( 'meta_key=_votemecount&amp;orderby=meta_value_num&amp;order=DESC&amp;posts_per_page='.$numberofpost );
	// The Loop
	while ( $the_query->have_posts() ) : $the_query->the_post();
	$output .= '<li>';
	$output .= '<a href="'.get_permalink(). '" rel="bookmark">'.get_the_title().'('.get_post_meta(get_the_ID(), '_votemecount', true).')'.'</a> ';
	$output .= '</li>';
	endwhile;
	wp_reset_postdata();
	return $output;
}

Then we create a widget which takes the number of post and the title from the user and uses the abpve function to display the top voted posts.

class VoteMeTopVotedWidget extends WP_Widget {

	function VoteMeTopVotedWidget() {
	// widget actual processes
	$widget_ops = array('classname' => 'VoteMeTopVotedWidget', 'description' => 'Widget for top voted Posts.' );
	$this->WP_Widget('VoteMeTopVotedWidget','VoteMeTopVotedWidget', $widget_ops);
}

function form($instance) {
	// outputs the options form on admin
	$defaults = array( 'title' => 'Top Voted Posts', 'numberofposts' => '5' );
	$instance = wp_parse_args( (array) $instance, $defaults );

	?>
	<p>
	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php echo 'Title:'; ?></label>
	<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" class="widefat" />
	</p>
	<p>
	<label for="<?php echo $this->get_field_id( 'numberofposts' ); ?>"><?php echo 'Number of Posts'; ?></label>
	<input id="<?php echo $this->get_field_id( 'numberofposts' ); ?>" name="<?php echo $this->get_field_name( 'numberofposts' ); ?>" value="<?php echo $instance['numberofposts']; ?>" class="widefat" />
	</p>

	<?php

}

function update($new_instance, $old_instance) {
	// processes widget options to be saved

	$instance = $old_instance;
	$instance['title'] = strip_tags( $new_instance['title'] );
	$instance['numberofposts'] = $new_instance['numberofposts'];
	return $instance;
}

function widget($args, $instance) {
	// outputs the content of the widget
	extract( $args );
	$title = apply_filters('widget_title', $instance['title'] );
	echo $before_widget;
	if ( $title )
	echo $before_title . $title . $after_title;

	echo '<ul>';
	echo voteme_get_highest_voted_posts($instance['numberofposts']);
	echo '</ul>';
	echo $after_widget;
}

}

function voteme_widget_init() {

	// Check for the required API functions
	if ( !function_exists('register_widget') )
	return;

	register_widget('VoteMeTopVotedWidget');
}

add_action('widgets_init', 'voteme_widget_init');</pre>

The widget will look as follows

8

On the front, the widget will look as follows

9

Conclusion.

With custom fields, WordPress makes it easy for us to extend it to use for different purposes. WordPress has good support for AJAX as we have seen in this tutorial. So, happy WordPress development!

说点什么

476 评论 在 "Create a Voting Plugin for WordPress"

提醒
排序:   最新 | 最旧 | 得票最多

wonderful publish, very informative. I wonder why the other experts
of this sector do not notice this. You should continue
your writing. I’m sure, you have a huge readers’ base
already!

VPB856 in accession capital to assert that I acquire in fact enjoyed account

Oh my goodness! an incredible article dude. Thanks Nonetheless I am experiencing problem with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting similar rss problem? Anyone who is aware of kindly respond. Thnkx

I simply wanted to construct a small remark in order to appreciate you for all the amazing points you are posting at this site. My prolonged internet investigation has finally been honored with incredibly good insight to exchange with my neighbours. I ‘d mention that many of us website visitors actually are quite lucky to dwell in a remarkable community with very many awesome professionals with interesting hints. I feel very much lucky to have come across the webpage and look forward to really more thrilling moments reading here. Thanks a lot once more for a lot of things.

I wish to express my respect for your kindness supporting persons who must have help with the matter. Your personal commitment to passing the message throughout appears to be wonderfully functional and has all the time helped professionals much like me to attain their objectives. Your new helpful publication indicates much a person like me and additionally to my peers. Thanks a ton; from everyone of us.

I am often to running a blog and i really respect your content. The article has actually peaks my interest. I am going to bookmark your website and hold checking for brand new information.

Spot on with this write-up, I truly suppose this web site wants way more consideration. I抣l most likely be again to learn much more, thanks for that info.

A powerful share, I just given this onto a colleague who was doing just a little analysis on this. And he actually bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying more on this topic. If possible, as you become experience, would you mind updating your weblog with more details? It is extremely useful for me. Huge thumb up for this weblog publish!

There are definitely a variety of details like that to take into consideration. That may be a nice level to carry up. I provide the thoughts above as normal inspiration however clearly there are questions like the one you deliver up the place crucial thing will likely be working in honest good faith. I don?t know if finest practices have emerged around issues like that, but I am sure that your job is clearly recognized as a good game. Both girls and boys feel the impression of just a second抯 pleasure, for the remainder of their lives.

Thank you so much for giving everyone an extraordinarily memorable possiblity to read from this blog. It can be very terrific and jam-packed with a good time for me personally and my office acquaintances to search the blog a minimum of thrice weekly to read through the fresh guides you have. And of course, I am usually fascinated with your excellent knowledge you give. Certain 4 tips in this post are undeniably the finest I have had.

Would you be keen on exchanging links?

This web page can be a stroll-via for all the info you wished about this and didn抰 know who to ask. Glimpse right here, and you抣l undoubtedly discover it.

I’m usually to blogging and i really recognize your content. The article has actually peaks my interest. I am going to bookmark your website and maintain checking for brand spanking new information.

A lot of thanks for each of your effort on this web site. Betty really likes setting aside time for research and it’s really obvious why. A number of us know all relating to the compelling manner you present simple ideas through this web blog and therefore foster participation from some other people on that idea so our favorite daughter is in fact starting to learn a great deal. Take advantage of the remaining portion of the year. Your carrying out a glorious job.

There are some attention-grabbing points in time on this article but I don抰 know if I see all of them center to heart. There is some validity however I’ll take maintain opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely

When I initially commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you possibly can remove me from that service? Thanks!

WONDERFUL Post.thanks for share..more wait .. ?

Matthewspoob
Lose up to 23 pounds of pure body fat in just 3 weeks!, how did i do that? The 3 Week Diet is an ext… 阅读更多 »

There are some fascinating time limits in this article however I don抰 know if I see all of them heart to heart. There is some validity but I will take hold opinion until I look into it further. Good article , thanks and we would like more! Added to FeedBurner as properly

I must express appreciation to this writer for rescuing me from this particular matter. Because of s… 阅读更多 »

When I originally commented I clicked the -Notify me when new feedback are added- checkbox and now each time a comment is added I get 4 emails with the identical comment. Is there any way you may take away me from that service? Thanks!

I抎 have to verify with you here. Which isn’t something I normally do! I get pleasure from reading a submit that will make individuals think. Also, thanks for permitting me to comment!

No matter if some one searches ffor his vital thing, therefore he/she desores to bee available that in detail,
sso that thing is maintained over here.

Youre so cool! I dont suppose Ive learn something like this before. So nice to search out any person with some original ideas on this subject. realy thanks for beginning this up. this web site is one thing that is needed on the internet, someone with a little originality. helpful job for bringing one thing new to the internet!

With havin so much written content do you ever run into
any problems of plagorism or copyright infringement? My site has a lot of exclussive content I’ve either crdeated
myself or outsourced but itt seems a lot of it iis popping it up all over the web without my authorization. Do you know any techhniques
to help protect against content from being ripped off?
I’d genuinely appreciate it.

Spot on with this write-up, I really assume this web site needs rather more consideration. I抣l in all probability be again to learn way more, thanks for that info.

I wanted to write you that little remark so as to thank you very much as before with your precious p… 阅读更多 »

you will have a great weblog right here! would you wish to make some invite posts on my weblog?

Hi terrific blog! Does running a blog similar to this require a massive amount work?
I have very little understanding of coding however I was hoping to start my own blog soon. Anyhow,
if you have any recommendations or tips for new blog
owners please share. I understand this is off subjedt however
I simply wanted to ask. Thank you!

I am usually to blogging and i actually respect your content. The article has actually peaks my interest. I’m going to bookmark your web site and keep checking for brand spanking new information.

I simply wished to say thanks again. I am not sure the things I would have sorted out without the actual smart ideas revealed by you on my area. This has been a very challenging matter in my view, however , seeing the very professional avenue you managed the issue forced me to weep over fulfillment. Now i’m happy for your assistance and then hope that you really know what a powerful job you are always carrying out instructing men and women thru your site. More than likely you have never encountered all of us.

This website online is mostly a walk-via for all the info you wanted about this and didn抰 know who to ask. Glimpse right here, and you抣l definitely uncover it.

This web page is really a walk-by means of for all the data you wished about this and didn抰 know who to ask. Glimpse here, and also you抣l positively discover it.

Youre so cool! I dont suppose Ive read something like this before. So good to search out any person with some original thoughts on this subject. realy thanks for starting this up. this website is one thing that is needed on the web, somebody with a bit of originality. helpful job for bringing something new to the internet!

I simply desired tto thank you so much all over again. I doo
not knnow what I would’ve achieved iin the absence of the methods
revwaled by you on my concern. Certainly was a real troublesome crisis in my opinion, but umderstanding the specialized strategy you managed that ade me too jump for contentment.
I will be happy for the advice and thus trust you find out what a great
job you were accomplishing teaching some other peopple thhru your blog post.
Most probsbly you have never encountered any of us.

Hi there! I know this is kinda off topic but I was wondering which blog platform are you using for this website?
I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform.

I would be awesome if you could point me in the direction of a good platform.

Insurance is a form of protection against loss of life and
property

address Go Compare Car Insurance Quotes car-insurance-quotes.co.inNavigate here
Young Female Car Insurance Quotes Car-Insurance-Quotes.co.in
read this post here Car Insurance Quotes Ma car-insurance-quotes.co.in

Hi there it’s me, I am also visiting this web site
regularly, this site is really good and the visitors are truly sharing nice thoughts.

I am only writing to make you be aware of what a amazing discovery my cousin’s child undergone reading through your web site. She even learned a lot of details, including what it’s like to possess an incredible helping mindset to get others without problems fully understand specified tricky things. You undoubtedly surpassed people’s expected results. Many thanks for imparting those powerful, trusted, edifying and also fun tips about this topic to Tanya.

Amazing things here. I am very hapopy too peer your article.

Thanks a lot and I am having a look ahhead to touch you. Will yoou kindly drop me a e-mail?

The following time I read a blog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my option to read, but I actually thought youd have one thing interesting to say. All I hear is a bunch of whining about one thing that you could fix in case you werent too busy looking for attention.

Wonderful post! We are linking to this great post on our site.
Keep up the great writing.

Heya i am for the first time here. I came across this board and I find It really useful & it helped
me out a lot. I hope to give something back and help
others like you aided me.

WOW just what I was searching for. Came here by searching for minecraft

Howdy! I simply want to give you a big thumbs
up for the great information you have here on this post.
I’ll be coming back to your website for more soon.

Please let me know if you’re looking for a article author for your
site. You have some really great articles and I feel I would be a good asset.
If you ever want to take some of the load off, I’d really
like to write some content for your blog in exchange for a link back to mine.
Please send me an email if interested. Thank you!

I know this website gives quality dependent content and other information, is there any other website which
gives these kinds of things in quality?

I just could not leave your web site prior to suggesting that I extremely loved the standard info a person supply to your visitors?
Is gonna be again steadily in order to investigate cross-check new posts

Why users still make use of to read news papers when in this technological globe everything is existing on web?

Why people still make use of to read news papers when in this technological globe everything is available on net?

Excellent post. I used to be checking constantly this weblog and I’m
impressed! Extremely helpful information specifically the ultimate phase 🙂 I handle such info
much. I used to be seeking this certain information for a very lengthy time.
Thank you and best of luck.

wpDiscuz