wordpress进阶教程(三十一):ajax实现文章顶踩


本篇教程要实现的内容为文章定踩功能,或者说“喜欢”“不喜欢”。

应用实例:

wordpress顶踩功能

实现步骤:

本实例以上图所示喜欢和不喜欢为例。

一、新建数据表

新建数据表,将文章投票数据保存在新的数据表中,我们需要记录用户ID,文章ID,投票内容,用户ip,新数据表如下:投票功能数据表

实现新建数据表代码如下,将代码添加进主题的functions.php(或自定)文件中:

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

二、准备投票和查询函数

准备数据库操作函数,包括添加数据函数和查询数据,将如下函数代码也添加到主题的functions.php文件(或自定):

1、添加数据函数

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

2、查询投票数据函数

比如查询某文章点击up的数据,则使用 get_post_vote(1,'up');

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

三、准备前台html和js

建立好了新的数据表,也准备好了实现投票功能的函数,接下来看前台的html和js。

1、网页前台显示数据,将下面的代码放在输出文章的循环内,即常说的loop中。

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

上面代码将会输出一个如下的html结构

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

四、js代码
本篇教程中和上一篇一样,我们同样使用jquery发起ajax请求,所以首先在网页头部加载jquery代码,我在主题底部文件footer.php中加载jqeury。我将jquery-1.7.2.min.js放在了主题文件夹的js文件夹里面,所以用get_template_directory_uri()函数来输出主题的url

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

然后我将发起ajax请求代码也放在了主题里面js文件夹中的ashu.js文件,所以再加上一个

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

ashu.js文件中的代码

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

五、后台php处理代码。

在前面的教程中,我们的ajax请求地址直接是网站页码地址,但是本篇教程中,我们的ajax请求地址是类似:www.shouce.ren/wp-admin/admin-ajax.php

使用这个地址来处理ajax请求,请一定记得请求中需要有action参数,然后我们只需要在functions.php文件(或自定)中添加下马代码,即可处理我们的请求,注意执行完请求输出内容之后,添加die函数结束:

  1. /*********更新重写规则***************/  
  2. function ashu_load_theme() {   
  3.     global $pagenow;   
  4.     if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )   
  5.         ashu_vote_install(); //激活主题的时候执行函数   
  6. }   
  7. add_action( 'load-themes.php', 'ashu_load_theme' );   
  8. function ashu_vote_install(){   
  9.     global $wpdb;   
  10.     //创建 _post_vote表   
  11.     $table_name = $wpdb->prefix . 'post_vote';   
  12.     if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :   
  13.     $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
  14.       `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
  15.       `user` INT NOT NULL ,  
  16.       `post` INT NOT NULL ,  
  17.       `rating` varchar(10),  
  18.       `ip` varchar(40)  
  19.      ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";   
  20.         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');   
  21.         dbDelta($sql);   
  22.     endif;   
  23. }  
  24. /*  
  25. *添加投票函数  
  26. *$post_id 文章id  
  27. *$user_id 用户ID  
  28. *$ip 用户IP  
  29. *$rating 投票内容  
  30. */  
  31. function add_vote($post_id,$user_id='',$ip='',$rating='up'){   
  32.     global $wpdb;   
  33.     $user_id = (int)$user_id;   
  34.     $post_id = (int)$post_id;   
  35.     if(($user_id=='')&&($ip=='')){   
  36.         return "e"; //返回error   
  37.     }   
  38.     //检查用户对某一文章是否已经投票票了   
  39.     if($user_id!=''){   
  40.         $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";   
  41.     }else{   
  42.         if($ip!=''){   
  43.             $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";   
  44.         }   
  45.     }   
  46.     $coo = $wpdb->get_results($check);   
  47.     //投票内容只能是up或者down   
  48.     if($rating=='up'){   
  49.         $rating='up';   
  50.     }else{   
  51.         $rating='down';   
  52.     }   
  53.     //如果不存在数据   
  54.     if(!count($coo) > 0){   
  55.         //插入数据 sql   
  56.         $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";   
  57.         $wpdb->query($s);   
  58.         return "y"; //返回yes   
  59.     }else{   
  60.         return "h"; //返回have   
  61.     }   
  62.     return "e";//返回error   
  63. }  
  64. /*   
  65. *获取文章投票数据   
  66. *$post_id 文章ID   
  67. *$vote 投票内容   
  68. */   
  69. function get_post_vote($post_id,$vote='up'){   
  70.     global $wpdb;   
  71.     $post_id = (int)$post_id;   
  72.     if($vote == 'up'){   
  73.         $vote='up';   
  74.     }else{   
  75.         $vote='down';   
  76.     }   
  77.     //查询数据sql   
  78.     $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";   
  79.     $coo = $wpdb->get_var($sql);   
  80.     if($coo)   
  81.     return $coo; //返回数据   
  82.     else   
  83.     return 0;   
  84. }  
  85. <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">   
  86.     <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">   
  87.     <span id="<?php echo 'vup'.$post->ID;?>">   
  88.         <?php echo get_post_vote($post->ID,'up');?>   
  89.     </span>   
  90.     </a>   
  91. 人认为值得买!</span>   
  92.   
  93. <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">   
  94.     <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">   
  95.     <span id="<?php echo 'vdown'.$post->ID;?>">   
  96.         <?php echo get_post_vote($post->ID,'down');?>   
  97.     </span>   
  98.     </a>人认为不值得买!   
  99. </span>  
  100. <span class="vote_up" id="vote_up44">  
  101.     <a href="javascript:void(0);" title="值得" rel="up_44">  
  102.     <span id="vup44">  
  103.         0   
  104.     </span>  
  105.     </a>  
  106. 人认为值得买!</span>  
  107. <span class="vote_down" id="vote_down44">  
  108.     <a href="javascript:void(0);" title="不值" rel="down_44">  
  109.     <span id="vdown44">  
  110.         1   
  111.     </span>  
  112.     </a>人认为不值得买!   
  113. </span>  
  114. <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>   
  115. 其中输出了ajax请求的地址:www.shouce.ren/wp-admin/admin-ajax.php
  116. <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>  
  117. <script src="<?php echo get_template_directory_uri();?>/js/ashu.js"></script>    
  118. /**     
  119.  * by ashu.     
  120.  * URI: http://www.shouce.ren     
  121.  */   
  122.   
  123. /**   
  124.  * 获取Cookie   
  125.  *name  cookie名称   
  126.  */   
  127. function getCookie(name) {   
  128.     var start = document.cookie.indexOf( name + "=" );   
  129.     var len = start + name.length + 1;   
  130.   
  131.     if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )   
  132.         return null;   
  133.   
  134.     if ( start == -1 )   
  135.         return null;   
  136.   
  137.     var end = document.cookie.indexOf( ';', len );   
  138.   
  139.     if ( end == -1 )   
  140.         end = document.cookie.length;   
  141.     return unescape( document.cookie.substring( len, end ) );   
  142. }   
  143. function ashu_isCookieEnable() {   
  144.     var today = new Date();   
  145.     today.setTime( today.getTime() );   
  146.     var expires_date = new Date( today.getTime() + (1000 * 60) );   
  147.   
  148.     document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';   
  149.     var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;   
  150.     //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';   
  151.     return cookieEnable;   
  152. }   
  153.     
  154. jQuery(document).ready(function($) {   
  155.     var ashu_token = 1;   
  156.     $('.vote_up a').click(function(){   
  157.         //检查浏览器是否启用cookie功能   
  158.         if( !ashu_isCookieEnable() ) {   
  159.             alert("很抱歉,您不能给本文投票!");   
  160.             return;   
  161.         }   
  162.         if( ashu_token != 1 ) {   
  163.             alert("您的鼠标点得也太快了吧?!");   
  164.             return false;   
  165.         }   
  166.         ashu_token = 0;   
  167.         //获取投票a标签中的rel值   
  168.         var full_info = $(this).attr( 'rel' );   
  169.         var arr_param = full_info.split( '_' ); //以字符"_"分割   
  170.         //发起ajax   
  171.         $.ajax({   
  172.             url:ajax_url, //ajax地址   
  173.             type:'POST',   
  174.             //请求的参数包括action   rating  postid三项   
  175.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  176.             //返回数据   
  177.             success:function(results){   
  178.                 if(results=='n'){   
  179.                     alert('评价失败');   
  180.                     ashu_token = 1;   
  181.   
  182.                 }   
  183.                 if (results=='y'){   
  184.                     //如果成功,给前台数据加1   
  185.                     var upd_vd = 'vup' + arr_param[ 1 ];   
  186.                     $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  187.                     ashu_token = 1;   
  188.                        
  189.                 }   
  190.                 if (results=='h'){   
  191.                     ashu_token = 1;   
  192.                     alert('已经发表过评价了');   
  193.                 }   
  194.                 if (results=='e'){   
  195.                     ashu_token = 1;   
  196.                     alert('评价失败');   
  197.                 }   
  198.             }   
  199.         });   
  200.     });   
  201.        
  202.     $('.vote_down a').click(function(){   
  203.         if( !ashu_isCookieEnable() ) {   
  204.             alert("很抱歉,您不能给本文投票!");   
  205.             return;   
  206.         }   
  207.         if(ashu_token != 1) {   
  208.             alert("您的鼠标点得也太快了吧?!");   
  209.             return false;   
  210.         }   
  211.         ashu_token = 0;   
  212.   
  213.         var full_info = $(this).attr( 'rel' );   
  214.         var arr_param = full_info.split( '_' );   
  215.         $.ajax({   
  216.             url:ajax_url,   
  217.             type:'POST',   
  218.             data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],   
  219.             success:function(results){   
  220.                 if(results=='n'){   
  221.                     alert('评价失败');   
  222.                     ashu_token = 1;   
  223.                 }   
  224.                 if (results=='y'){   
  225.                     var upd_vd = 'vdown' + arr_param[ 1 ];   
  226.                     $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);   
  227.                     ashu_token = 1;   
  228.                 }   
  229.                 if (results=='h'){   
  230.                     ashu_token = 1;   
  231.                     alert('已经发表过评价了');   
  232.                 }   
  233.                 if (results=='e'){   
  234.                     ashu_token = 1;   
  235.                     alert('发生未知错误');   
  236.                 }   
  237.             }   
  238.         });   
  239.     });   
  240. });  
  241. /*   
  242. *wp的ajax都可以通过请求中的action参数来执行对应的钩子   
  243. *示例中我们的action参数值是vote_post   
  244. *所以我们可以直接用下面两个钩子来执行动作   
  245. */   
  246. add_action("wp_ajax_vote_post", "add_votes_options");   
  247. add_action("wp_ajax_nopriv_vote_post", "add_votes_options");   
  248. function add_votes_options() {   
  249.   
  250. if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){   
  251.     $postid = (int)$_POST['postid'];   
  252.     if( !$postid ){   
  253.         echo 'e'; //输出error   
  254.         die(0);   
  255.     }   
  256.     //cookie中是否已经存在投票数据   
  257.     $voted = $_COOKIE["smzdm_voted_".$postid];   
  258.     if( $voted ){   
  259.         echo 'h'; //输出have   
  260.         die(0);   
  261.     }   
  262.     $ip = $_SERVER['REMOTE_ADDR'];//ip   
  263.     $rating = $_POST['rating']; //投票内容   
  264.     //判断用户是否登录   
  265.     if(  is_user_logged_in() ){   
  266.         global $wpdb, $current_user;   
  267.         get_currentuserinfo();   
  268.         $uid = $current_user->ID;   
  269.     }else{   
  270.         $uid='';   
  271.     }   
  272.     if($rating=='up'){   
  273.         $rating='up';   
  274.     }else{   
  275.         $rating='down';   
  276.     }   
  277.     //添加数据   
  278.     $voted = add_vote($postid,$uid,$ip,$rating);   
  279.     if($voted=='y'){   
  280.         //设置cookie   
  281.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  282.         echo 'y';//输出yes   
  283.         die(0);   
  284.     }   
  285.     if($voted=='h'){   
  286.         //设置cookie   
  287.         setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');   
  288.         echo 'h';   
  289.         die(0);   
  290.     }   
  291.     if($voted=='e'){   
  292.         echo 'n';//输出no   
  293.         die(0);   
  294.     }   
  295. }else{   
  296.     echo 'e';//输出eroor   
  297. }   
  298. die(0);   
  299. }  

六、结束
本票教程并非实现定踩或喜欢功能的最佳选择,只是提供一个ajax的简单示例...