为了增加wordpress的互动性,在很多时候,我们会给一篇文章添加wordpress顶和踩功能,而这样一个简单的功能,我们可以通过插件来完成,但是比较好的插件并不多,要么是收费的,要么就是死位置的,不灵活,小编在最近写的一款笑话类wordpress主题的时候,也遇到这个问题,百度了很久,终究还是完成了wordpress顶和踩功能的实现!
教程说明
1、新建数据表
首先我们必须要新建一个数据表来储存文章投票的数据,我们必须要获取用户、文章的ID、投票内容等信息。。。
恩,创建数据表的方法如下代码,放入到wordpress主题的根目录functions.php文件内
- /*********更新重写规则***************/
- function ashu_load_theme() {
- global $pagenow;
- if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )
- ashu_vote_install(); //激活主题的时候执行函数
- }
- add_action( 'load-themes.php', 'ashu_load_theme' );
- function ashu_vote_install(){
- global $wpdb;
- //创建 _post_vote表
- $table_name = $wpdb->prefix . 'post_vote';
- if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :
- $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
- `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
- `user` INT NOT NULL ,
- `post` INT NOT NULL ,
- `rating` varchar(10),
- `ip` varchar(40)
- ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";
- require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
- dbDelta($sql);
- endif;
- }
2、准备投票和查询函数
然后我们要准备好投票的数据函数和数据查询函数,同样将如下代码放入functions.php文件内
a、数据函数的添加
- /*
- *添加投票函数
- *$post_id 文章id
- *$user_id 用户ID
- *$ip 用户IP
- *$rating 投票内容
- */
- function add_vote($post_id,$user_id='',$ip='',$rating='up'){
- global $wpdb;
- $user_id = (int)$user_id;
- $post_id = (int)$post_id;
- if(($user_id=='')&&($ip=='')){
- return "e"; //返回error
- }
- //检查用户对某一文章是否已经投票票了
- if($user_id!=''){
- $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";
- }else{
- if($ip!=''){
- $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";
- }
- }
- $coo = $wpdb->get_results($check);
- //投票内容只能是up或者down
- if($rating=='up'){
- $rating='up';
- }else{
- $rating='down';
- }
- //如果不存在数据
- if(!count($coo) > 0){
- //插入数据 sql
- $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";
- $wpdb->query($s);
- return "y"; //返回yes
- }else{
- return "h"; //返回have
- }
- return "e";//返回error
- }
b、数据查询函数的添加
- /*
- *获取文章投票数据
- *$post_id 文章ID
- *$vote 投票内容
- */
- function get_post_vote($post_id,$vote='up'){
- global $wpdb;
- $post_id = (int)$post_id;
- if($vote == 'up'){
- $vote='up';
- }else{
- $vote='down';
- }
- //查询数据sql
- $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";
- $coo = $wpdb->get_var($sql);
- if($coo)
- return $coo; //返回数据
- else
- return 0;
- }
3、整理前台的html和js调用
将上面的函数的创建后,后面我们就要输出wordpress顶和踩功能的前台代码了!
a、前台函数输出
- <span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">
- <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">
- <span id="<?php echo 'vup'.$post->ID;?>">
- <?php echo get_post_vote($post->ID,'up');?>
- </span>
- </a>
- 顶</span>
- <span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">
- <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">
- <span id="<?php echo 'vdown'.$post->ID;?>">
- <?php echo get_post_vote($post->ID,'down');?>
- </span>
- </a>踩
- </span>
将上面的代码放到我们需要显示wordpress顶和踩功能的地方,通过上面的函数代码得出了下面输出的html,大家适量的修改即可!
b、前台函数输出
- <span class="vote_up" id="vote_up44">
- <a href="javascript:void(0);" title="值得" rel="up_44">
- <span id="vup44">
- 0
- </span>
- </a>
- 顶</span>
- <span class="vote_down" id="vote_down44">
- <a href="javascript:void(0);" title="不值" rel="down_44">
- <span id="vdown44">
- 1
- </span>
- </a>踩
- </span>
c、js的调用
在wordpress主题文件的footer.php里加入
- <script src="<?php echo get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>
- <script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>
- <script src="<?php echo get_template_directory_uri();?>/js/ding.js"></script>
其中,jquery-1.7.2.min.js可以到网上下载,或者大家的主题里已经提供,那么就不需要调用,下面我们在主题文件夹的js文件下新建个ding.js,没有的创建一下,下面是ding.js的内容:
- /**
- * ding
- */
- function getCookie(name) {
- var start = document.cookie.indexOf( name + "=" );
- var len = start + name.length + 1;
- if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
- return null;
- if ( start == -1 )
- return null;
- var end = document.cookie.indexOf( ';', len );
- if ( end == -1 )
- end = document.cookie.length;
- return unescape( document.cookie.substring( len, end ) );
- }
- function ashu_isCookieEnable() {
- var today = new Date();
- today.setTime( today.getTime() );
- var expires_date = new Date( today.getTime() + (1000 * 60) );
- document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';
- var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ? true : false;
- //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';
- return cookieEnable;
- }
- jQuery(document).ready(function($) {
- var ashu_token = 1;
- $('.vote_up a').click(function(){
- //检查浏览器是否启用cookie功能
- if( !ashu_isCookieEnable() ) {
- alert("很抱歉,您不能给本文投票!");
- return;
- }
- if( ashu_token != 1 ) {
- alert("您的鼠标点得也太快了吧?!");
- return false;
- }
- ashu_token = 0;
- //获取投票a标签中的rel值
- var full_info = $(this).attr( 'rel' );
- var arr_param = full_info.split( '_' ); //以字符"_"分割
- //发起ajax
- $.ajax({
- url:ajax_url, //ajax地址
- type:'POST',
- //请求的参数包括action rating postid三项
- data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],
- //返回数据
- success:function(results){
- if(results=='n'){
- alert('评价失败');
- ashu_token = 1;
- }
- if (results=='y'){
- //如果成功,给前台数据加1
- var upd_vd = 'vup' + arr_param[ 1 ];
- $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);
- ashu_token = 1;
- }
- if (results=='h'){
- ashu_token = 1;
- alert('已经发表过评价了');
- }
- if (results=='e'){
- ashu_token = 1;
- alert('评价失败');
- }
- }
- });
- });
- $('.vote_down a').click(function(){
- if( !ashu_isCookieEnable() ) {
- alert("很抱歉,您不能给本文投票!");
- return;
- }
- if(ashu_token != 1) {
- alert("您的鼠标点得也太快了吧?!");
- return false;
- }
- ashu_token = 0;
- var full_info = $(this).attr( 'rel' );
- var arr_param = full_info.split( '_' );
- $.ajax({
- url:ajax_url,
- type:'POST',
- data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],
- success:function(results){
- if(results=='n'){
- alert('评价失败');
- ashu_token = 1;
- }
- if (results=='y'){
- var upd_vd = 'vdown' + arr_param[ 1 ];
- $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);
- ashu_token = 1;
- }
- if (results=='h'){
- ashu_token = 1;
- alert('已经发表过评价了');
- }
- if (results=='e'){
- ashu_token = 1;
- alert('发生未知错误');
- }
- }
- });
- });
- });
4、最终后台的php处理
将代码放到functions.php完成处理ajax请求,
- /*
- *wp的ajax都可以通过请求中的action参数来执行对应的钩子
- *示例中我们的action参数值是vote_post
- *所以我们可以直接用下面两个钩子来执行动作
- */
- add_action("wp_ajax_vote_post", "add_votes_options");
- add_action("wp_ajax_nopriv_vote_post", "add_votes_options");
- function add_votes_options() {
- if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){
- $postid = (int)$_POST['postid'];
- if( !$postid ){
- echo 'e'; //输出error
- die(0);
- }
- //cookie中是否已经存在投票数据
- $voted = $_COOKIE["smzdm_voted_".$postid];
- if( $voted ){
- echo 'h'; //输出have
- die(0);
- }
- $ip = $_SERVER['REMOTE_ADDR'];//ip
- $rating = $_POST['rating']; //投票内容
- //判断用户是否登录
- if( is_user_logged_in() ){
- global $wpdb, $current_user;
- get_currentuserinfo();
- $uid = $current_user->ID;
- }else{
- $uid='';
- }
- if($rating=='up'){
- $rating='up';
- }else{
- $rating='down';
- }
- //添加数据
- $voted = add_vote($postid,$uid,$ip,$rating);
- if($voted=='y'){
- //设置cookie
- setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');
- echo 'y';//输出yes
- die(0);
- }
- if($voted=='h'){
- //设置cookie
- setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');
- echo 'h';
- die(0);
- }
- if($voted=='e'){
- echo 'n';//输出no
- die(0);
- }
- }else{
- echo 'e';//输出eroor
- }
- die(0);
- }
到这里,教程算是结束了,要提醒大家的是,功能集成到主题后,需要将主题重新安装后,数据表才会被添加!OK。。。大家尝试吧!