This tutorial demonstrates building a WordPress plugin, "Vote Me," to add voting functionality to posts and display top-voted content.
Key Features:
-
Custom Voting Plugin: A
voteme.php
plugin file handles core functionality, including AJAX integration viavoteme.js
. - Post Voting: A voting link beneath each post dynamically updates vote counts using AJAX.
- Admin Panel Integration: The WordPress admin displays and sorts posts by vote count.
- Registered User Restriction: Voting is limited to registered, logged-in users to prevent spam.
- Top Voted Posts Widget: A customizable widget showcases the most popular posts.
Plugin Creation:
Create voteme.php
within your wp-content/plugins/voteme
directory. The plugin header should be:
<?php /* Plugin Name: Vote Me Plugin URI: [Your Plugin URI] Description: Adds voting to posts. Author: Abbas Version: 0.1 Author URI: [Your Author URI] */ define('VOTEMESURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) ); define('VOTEMEPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );
Create a js
folder within voteme
and add voteme.js
. The plugin structure should resemble this:
Enqueue the scripts:
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');
Activate the plugin in the WordPress admin panel.
Adding Vote Links:
Add a vote link to posts:
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>' . $link . '</div>'; } else { $register_link = site_url('wp-login.php'); $votemelink = '<div><a href="' . $register_link . '">Vote</a></div>'; } return $votemelink; } function voteme_printvotelink($content) { return $content . voteme_getvotelink(); } add_filter('the_content', 'voteme_printvotelink');
This adds the vote count and link below each post.
AJAX Voting:
voteme.js
:
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); } }); }
voteme.php
:
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>' . $votemecountNew . '</div>'; die($results); } add_action( 'wp_ajax_nopriv_voteme_addvote', 'voteme_addvote' ); add_action( 'wp_ajax_voteme_addvote', 'voteme_addvote' );
This handles the AJAX request to increment the vote count.
(The remaining sections detailing admin customization, sorting, user restriction, and widget creation are too extensive to include here. The provided text gives the complete code for each step. Please refer to the original input for the complete code snippets.)
The final sections cover adding a vote count column to the admin posts list, making it sortable, restricting voting to registered users via a settings page, and creating a widget to display the top-voted posts. All the necessary code is present in the original input. Remember to replace placeholder URIs with your own.
The above is the detailed content of Create a Voting Plugin for WordPress. For more information, please follow other related articles on the PHP Chinese website!

WordPresscanbeusedforvariouspurposesbeyondblogging.1)E-commerce:WithWooCommerce,itcanbecomeafullonlinestore.2)Membershipsites:PluginslikeMemberPressenableexclusivecontentareas.3)Portfoliosites:ThemeslikeAstraallowstunninglayouts.Ensuretomanageplugins

Yes,WordPressisexcellentforcreatingaportfoliowebsite.1)Itoffersnumerousportfolio-specificthemeslike'Astra'foreasycustomization.2)Pluginssuchas'Elementor'enableintuitivedesign,thoughtoomanycanslowthesite.3)SEOisenhancedwithtoolslike'YoastSEO',boosting

WordPressisadvantageousovercodingawebsitefromscratchdueto:1)easeofuseandfasterdevelopment,2)flexibilityandscalability,3)strongcommunitysupport,4)built-inSEOandmarketingtools,5)cost-effectiveness,and6)regularsecurityupdates.Thesefeaturesallowforquicke

WordPressisaCMSduetoitseaseofuse,customization,usermanagement,SEO,andcommunitysupport.1)Itsimplifiescontentmanagementwithanintuitiveinterface.2)Offersextensivecustomizationthroughthemesandplugins.3)Providesrobustuserrolesandpermissions.4)EnhancesSEOa

Enable comments on your WordPress website to provide visitors with a platform to participate in discussions and share feedback. To do this, follow these steps: Enable Comments: In the dashboard, navigate to Settings > Discussions, and select the Allow Comments check box. Create a comment form: In the editor, click Add Block and search for the Comments block to add it to the content. Custom Comment Form: Customize comment blocks by setting titles, labels, placeholders, and button text. Save changes: Click Update to save the comment box and add it to the page or article.

How to copy WordPress subsites? Steps: Create a sub-site in the main site. Cloning the sub-site in the main site. Import the clone into the target location. Update the domain name (optional). Separate plugins and themes.

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use <?php comments_template(); ?> tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools
