Skip to main content
We are Brand SEO Beijing serving international business, your marketing partner, Contact us by

Ajax realizes article top step: like it or not

The content to be implemented in this application tutorial is the article rating function, or "like" or "dislike".
Implementation steps:
In this example, the likes and dislikes shown in the figure above are examples.

XNUMX. Create a new data table

Create a new data table and save the article voting data in the new data table. We need to record the user ID, article ID, voting content, and user ip. The new data table is as follows:

/*********Update rewrite rules****************/ function ashu_load_theme() { global $pagenow; if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) ashu_vote_install(); //Execute the function when the theme is activated} add_action( 'load-themes.php', 'ashu_load_theme' ); function ashu_vote_install(){ global $wpdb; //Create _post_vote table $table_name = $wpdb->prefix . 'post_vote'; if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) : $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` ( `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY , `user` INT NOT NULL , `post` INT NOT NULL , `rating` varchar(10), `ip` varchar(40) ) ENGINE = MYISAM DEFAULT CHARSET=utf8;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); endif; }

XNUMX. Prepare voting and query functions

To prepare database operation functions, including adding data functions and querying data, add the following function codes to the theme's functions.php file (or customize):

1. Add data function
/* *Add voting function*$post_id Post id *$user_id User ID *$ip User IP *$rating Voting content*/ function add_vote($post_id,$user_id='',$ip='',$rating=' up'){ global $wpdb; $user_id = (int)$user_id; $post_id = (int)$post_id; if(($user_id=='')&&($ip=='')){ return "e "; //return error } //check if the user has voted for a post if($user_id!=''){ $check= "select * from ".$wpdb->prefix."post_vote where post= '$post_id' and user='$user_id'"; }else{ if($ip!=''){ $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'"; } } $coo = $wpdb->get_results($check); //The voting content can only be up or down if($rating=='up'){ $rating='up '; }else{ $rating='down'; } //If there is no data if(!count($coo) > 0){ //Insert data sql $s = "insert into ".$wpdb->prefix. "post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')"; $wpdb->query($s); return "y"; //return yes }else{ return "h"; //return have } return "e";//return error }
2. Query voting data function

For example, to query the data of an article clicking up, use get_post_vote(1,'up');

/* *Get post vote data*$post_id post ID *$vote vote content*/ function get_post_vote($post_id,$vote='up'){ global $wpdb; $post_id = (int)$post_id; if($vote == 'up'){ $vote='up'; }else{ $vote='down'; } //Query data sql $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'"; $coo = $wpdb->get_var($sql); if($coo) return $coo; //return data else return 0; }

XNUMX. Prepare front-end html and js

The new data table is established, and the function to implement the voting function is also ready. Next, look at the html and js in the foreground.
1. Display the data in the foreground of the webpage, and put the following code in the loop of outputting the article, which is often called the loop.

ID;?>">ID;?>">ID;?>">ID,'up');?> Like-Up! ID;?>">ID;?>">ID;?>">ID,'down');?> dislike - step down!

The above code will output an html structure as follows

44 likes - top! 0 dislike - step on!

XNUMX. js code

In this tutorial, like the previous one, we also use jquery to initiate ajax requests, so first load the jquery code at the head of the web page, and I load jqeury in the footer.php file at the bottom of the theme.I put jquery-1.7.2.min.js in the js folder of the theme folder, so I use the get_template_directory_uri() function to output the url of the theme


Then I put the code for initiating the ajax request in the likeornot.js file in the js folder in the theme, so add a
The address of the ajax request is output:

var ajax_url = 'admin-ajax.php';

code in likeornot.js file

/** * author:ashuwp * URI: */ /** * Get Cookie *name cookie name*/ function getCookie(name) { var start = document.cookie.indexOf( name + "=" ) ; var len = start + name.length + 1; if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) return null; if ( start == -1 ) return null ; var end = document.cookie.indexOf( ';', len ); if ( end == -1 ) end = document.cookie.length; return unescape( document.cookie.substring( len, end ) ); } function ashu_isCookieEnable() { var today = new Date(); today.setTime( today.getTime() ); var expires_date = new Date( today.getTime() + (1000 * 60) ); document.cookie = 'ashu_cookie_test=test ;expires=' + expires_date.toGMTString() + ';path=/'; var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ? 

Five, the background php processing code.

In the previous tutorial, our ajax request address is directly the website page number address, but in this tutorial, our ajax request address is similar:
Use this address to process ajax requests, please remember that the action parameter is required in the request, and then we only need to add the dismounting code in the functions.php file (or custom) to process our request, pay attention to the output content of the request after execution After that, adding the die function ends:

/* *wp's ajax can execute the corresponding hook through the action parameter in the request * in the example our action parameter value is vote_post * so we can directly use the following two hooks to execute the action */ add_action("wp_ajax_vote_post", "add_votes_options"); add_action("wp_ajax_nopriv_vote_post", "add_votes_options"); function add_votes_options() { if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){ $postid = (int)$_POST['postid']; if( !$postid ){ echo 'e'; //Output error die(0); } //Whether the voting data already exists in the cookie $voted = $_COOKIE ["smzdm_voted_".$postid]; if( $voted ){ echo 'h'; //output have die(0); } $ip = $_SERVER['REMOTE_ADDR'];//ip $rating = $_POST[ 'rating']; //Vote content//Determine whether the user is logged in if( is_user_logged_in() ){ global $wpdb, $current_user; get_currentuserinfo(); $uid = $current_user->ID; }else{ $uid='' ; } if($rating=='up'){ $rating='up'; }else{ $rating='down'; } //Add data $voted = add_vote($postid,$uid,$ip,$ rating); if($voted=='y'){ //set cookie setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/'); echo 'y';//output yes die(0); } if($voted=='h'){ //Set cookie setcookie("ashu_voted_" . $postid,$rating, time() + 3000000 0, '/'); echo 'h'; die(0); } if($voted=='e'){ echo 'n';//output no die(0); } }else{ echo 'e ';//output eroor } die(XNUMX); }

Six, the end

The promissory note tutorial is not the best choice for implementing a downvote or like function, it just provides a simple example of ajax...

Back to Top