如何用代码方式实现WordPress文章点赞

为了实现更好的互动效果,近期对Msimple主题进行了升级,增加了文章点赞功能,此功能参考了创客云的一篇文章纯代码WordPress文章添加点赞功能,在此记录和分享一下。

实现思路

通过 ajax 实时显示点赞数量,自定义字段保存赞数量,Cookies 禁止重新点赞。

添加代码

下方代码添加到主题的functions.php中:

add_action('wp_ajax_nopriv_bigfa_like', 'bigfa_like');
add_action('wp_ajax_bigfa_like', 'bigfa_like');
function bigfa_like(){
    global $wpdb,$post;
    $id = $_POST["um_id"];
    $action = $_POST["um_action"];
    if ( $action == 'ding'){
    $bigfa_raters = get_post_meta($id,'bigfa_ding',true);
    $expire = time() + 99999999;
    $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost
    setcookie('bigfa_ding_'.$id,$id,$expire,'/',$domain,false);
    if (!$bigfa_raters || !is_numeric($bigfa_raters)) {
        update_post_meta($id, 'bigfa_ding', 1);
    } 
    else {
            update_post_meta($id, 'bigfa_ding', ($bigfa_raters + 1));
        }

    echo get_post_meta($id,'bigfa_ding',true);

    } 

    die;
}

将下面的代码添加到主题的footer.php中,此代码依赖于jQuery,因此请确保您已经提前引入jQuery,否则不能正常使用。

<script type="text/javascript">
$.fn.postLike = function() {
    if ($(this).hasClass('done')) {
        return false;
    } else {
        $(this).addClass('done');
        var id = $(this).data("id"),
        action = $(this).data('action'),
        rateHolder = $(this).children('.count');
        var ajax_data = {
            action: "bigfa_like",
            um_id: id,
            um_action: action
        };
        $.post("/wp-admin/admin-ajax.php", ajax_data,
        function(data) {
            $(rateHolder).html(data);
        });
        return false;
    }
};
$(document).on("click", ".favorite",
function() {
    $(this).postLike();
});
</script>

修改文章页面single.php,在你需要的位置添加一个点赞按钮,代码如下:

<a href="javascript:;" rel="external nofollow" target = "_blank"  rel="external nofollow" target = "_blank"  data-action="ding" data-id="<?php the_ID(); ?>" class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>">喜欢 <span class="count">
   <?php if( get_post_meta($post->ID,'bigfa_ding',true) ){            
       echo get_post_meta($post->ID,'bigfa_ding',true);
   } else {
       echo '0';
   }?>
</span>
</a>

通过上面的三段代码就已经实现文章点赞功能,但是样式效果惨不忍睹,作者还提供了下面的样式,添加到主题style.css中(下方样式xiaoz未经测试)

.post-like{text-align:center;padding:10px}
.post-like a{ background-color:#21759B;border-radius: 3px;color: #FFFFFF;font-size: 12px;padding: 5px 10px;text-decoration: none;outline:none}
.post-like a.done, .post-like a:hover{background-color:#eee;color:#21759B;} 
.post-like a.done{cursor:not-allowed}

但是每个主题的风格可能不一样,上面的CSS样式不一定适合,建议大家根据自己的主题风格编写CSS样式(需要一定前端基础)

改进

上述方法是通过PHP判断COOKIE是否存在从而改变class属性,再判断按钮是否可以点击。但如果您网站启用了CDN,或使用了WP-Super-Cache这类静态缓存插件后,页面会被提前缓存起来,这样判断也就失效了,便可以无限点赞,于是xiaoz进行了改进,通过js再判断一次COOKIES是否存在,代码如下。

在主题页面single.php合适的位置添加如下代码:

<a id = "praise" data-no-instant class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>" href="javascript:;" rel="external nofollow" target = "_blank"  rel="external nofollow" target = "_blank"  data-action="ding" data-id="<?php the_ID(); ?>"><i class="fa fa-thumbs-o-up"></i> 赞 <span class="count">
                                       <?php if( get_post_meta($post->ID,'bigfa_ding',true) ){            
                                           echo get_post_meta($post->ID,'bigfa_ding',true);
                                       } else {
                                           echo '0';
                                       }?>
                                    </span>
                                    </a>

在主题页面底部footer.php添加如下代码(依赖于jQuery):

<script type="text/javascript">
//获取cookie
function getCookie(cookieName){  
    var cookieValue="";  
    if (document.cookie && document.cookie != '') {   
        var cookies = document.cookie.split(';');  
        for (var i = 0; i < cookies.length; i++) {   
             var cookie = cookies[i];  
             if (cookie.substring(0, cookieName.length + 2).trim() == cookieName.trim() + "=") {  
                   cookieValue = cookie.substring(cookieName.length + 2, cookie.length);   
                   break;  
             }  
         }  
    }   
    return cookieValue;  
}
$.fn.postLike = function() {
    if ($(this).hasClass('done')) {
        return false;
    } else {
        $(this).addClass('done');
        var id = $(this).data("id"),
        action = $(this).data('action'),
        rateHolder = $(this).children('.count');
        var ajax_data = {
            action: "bigfa_like",
            um_id: id,
            um_action: action
        };
        $.post("/wp-admin/admin-ajax.php", ajax_data,
        function(data) {
            $(rateHolder).html(data);
            $("#praise").removeClass("layui-btn-danger").addClass("layui-bg-gray");
        });
        return false;
    }
};
$(document).on("click", ".favorite",
function() {
    var post_id = $("#praise").attr("data-id");
    //获取COOKIE
    if ( getCookie('bigfa_ding_' + post_id) != '' ){
        alert('您已经点过赞了!);
    }
    else{
        $(this).postLike();
    }
});
</script>

总结

最后实现的功能类似小z博客文章下方的点赞效果,这里主要提供思路和代码实现,实际还得根据自身情况调整和修改代码,对开发者而言应该不难。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 WordPress 提供的 `wp_set_post_tags()` 函数来为文章添加标签。你可以在文章发布或更新时触发此函数,并将标签作为参数传递给它。 以下是一个简单的示例代码: ```php // 在文章发布或更新时触发 add_action('save_post', 'add_tags_to_post'); function add_tags_to_post($post_id) { // 检查是否为文章类型 if(get_post_type($post_id) != 'post') { return; } // 获取文章对象 $post = get_post($post_id); // 获取文章内容 $content = $post->post_content; // 将文章内容转换为标签数组 $tags = get_tags_from_content($content); // 为文章添加标签 if(!empty($tags)) { wp_set_post_tags($post_id, $tags, true); } } function get_tags_from_content($content) { // 从文章内容中提取标签 // 你可以编写自己的提取逻辑 // 这里只是一个示例 preg_match_all('/<tag>(.*?)<\/tag>/', $content, $matches); // 返回标签数组 return $matches[1]; } ``` 在上面的代码中,我们定义了一个 `add_tags_to_post()` 函数,它会在文章发布或更新时被触发。我们首先检查文章类型,然后获取文章对象和内容。接着,我们调用了 `get_tags_from_content()` 函数,该函数将文章内容转换为标签数组。最后,我们调用了 `wp_set_post_tags()` 函数,将标签数组添加到文章中。 需要注意的是,`get_tags_from_content()` 函数中的正则表达式只是一个示例。你需要根据自己的需求编写自己的提取逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值