当前位置: 首页 » 笔记 » wordpress非插件点赞功能

wordpress非插件点赞功能

零分笔记2,3322023-02-04 20:42

非插件wordpress点赞功能,其实就是调用wordpress自定义字段,通过AJAX提交修改wordpress字段的数值,和阅读次数差不多。

上图是最近写一个模版的文章底部的样式,现在帖下百度来的点赞代码:

1、在模版functions.php适合位置插入

//文章点赞开始  
add_action('wp_ajax_nopriv_specs_zan', 'specs_zan');  
add_action('wp_ajax_specs_zan', 'specs_zan');  
function specs_zan(){  
    global $wpdb,$post;  
    $id = $_POST["um_id"];  
    $action = $_POST["um_action"];  
    if ( $action == 'ding'){  
        $specs_raters = get_post_meta($id,'specs_zan',true);  
        $expire = time() + 99999999;  
        $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost  
        setcookie('specs_zan_'.$id,$id,$expire,'/',$domain,false);  
        if (!$specs_raters || !is_numeric($specs_raters)) {  
            update_post_meta($id, 'specs_zan', 1);  
        }  
        else {  
            update_post_meta($id, 'specs_zan', ($specs_raters + 1));  
        }  
        echo get_post_meta($id,'specs_zan',true);  
    }  
    die;  
}  
//文章点赞结束  

文章模版页添加JS代码:

$.fn.postLike = function() {  
    if ($(this).hasClass('done')) {  


        return false;  
    } else {  
        $(this).addClass('done');  
        $(this).children('.zan').html("已赞");  
        var id = $(this).data("id"),  
        action = $(this).data('action'),  
        rateHolder = $(this).children('.count');  
        var ajax_data = {  
            action: "specs_zan",  
            um_id: id,  
            um_action: action  
        };  
        $.post("/wp-admin/admin-ajax.php", ajax_data,  
        function(data) {  
            $(rateHolder).html(data);  
        });  
        return false;  
    }  
};  
$(document).on("click", ".specsZan",  
    function() {  
        $(this).postLike();  
});  

在文章模版页需要添加点赞按钮的地方添加代码:

<a hidefocus= true href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" class="specsZan <?php if(isset($_COOKIE['specs_zan_'.$post->ID])) echo 'done';?>">  
<i></i>  
<span class="zan" style="margin-right:5px;"><?php if(isset($_COOKIE['specs_zan_'.$post->ID])){ echo '已赞';}else{echo '赞';}?></span><span class="count"><?php if( get_post_meta($post->ID,'specs_zan',true) ){echo get_post_meta($post->ID,'specs_zan',true);} else {echo '0';}?></span></a></div>  

这样,一个wordpress非插件的点赞功能就出来了!CSS样式自行添加。

如果嫌麻烦,可以搜索安装相关的点赞插件,相对来说,非插件自定义的自由会比较大吧

END
零分站龄17年资深站长
一个喜欢折腾,却又折腾不出像样东西的,不会PHP的PHP程序员!
2517
文章
13
分类
3818
标签
3
友链
onlinelovesky317355746vipsever@vip.qq.com