加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > CMS系统 > wordpress > 正文

给WordPress分类\标签页面增加点赞功能

发布时间:2020-12-14 14:26:54 所属栏目:wordpress 来源:网络整理
导读:由站长 通过网络收集整理的代码片段。编程之家小编现在分享给大家,也给大家做个参考。 首先说明 wordpress AJAX 给 WordPress 主题分类标签页面增加点赞功能或者是 WordPress 文章点赞都会给数据库增加表,自 WordPress 4.4 新增了 Term me

以下代码由PHP站长网 52php.cn收集自互联网现在PHP站长网小编把它分享给大家,仅供参考

首先说明 wordpress AJAX 给 WordPress 主题分类标签页面增加点赞功能或者是 WordPress 文章点赞都会给数据库增加表,自 WordPress 4.4 新增了 Term meta,意味着可以像文章点赞一样来实现分类标签页面增加点赞功能,wordpress 当前把下面的代码加入到 functions.php:

function wp_term_like( $preifx = null){

global $wp_query;

if(!is_tax() && !is_category() && !is_tag()) return ;

$tax = $wp_query->get_queried_object();

$id = $tax->term_id;

$num = get_term_meta($id,'_term_like',true) ? get_term_meta($id,true) : 0;

$active = isset($_COOKIE['_term_like_'.$id]) ? ' is-active' : '';

$output = '<button class="button termlike' . $active . '" data-action="termlike" data-action-id="' . $id . '">' . $prefix . '<span class="count">' . $num . '</span></button>';

echo $output;

}

?

add_action('wp_ajax_nopriv_termlike','wp_term_like_callback');

add_action('wp_ajax_termlike','wp_term_like_callback');

function wp_term_like_callback(){

$id = $_POST['actionId'];

$num = get_term_meta($id,true) : 0;

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost

setcookie('_term_like_'.$id,$id,$expire,'/',$domain,false);

update_term_meta($id,$num + 1);

echo json_encode(array(

'status'=>200,

'data'=> $num + 1,

));

die;

}

AJAX js 代码加入的你的 js 文件中,注意 admin-ajax.php 的路径!

jQuery(document).on("click",".termlike",function() {

var _self = jQuery(this);

if (_self.hasClass('is-active')) {

alert('您已经赞过啦')

} else {

_self.addClass('is-active');

jQuery.ajax({

url: /wp-admin/admin-ajax.php,//注意你的该文件路径

data: _self.data(),

type: 'POST',

dataType: "json",

success: function(data) {

if (data.status === 200) {

_self.find('.count').html(data.data)

} else {

alert('服务器正在努力找回自我')

}

}

})

}

});

完成以上所有的操作以后,我们开始讲 WordPress 分类/标签页面点赞调用方法:

<?php wp_term_like();?>

在对应归档页面使用下面代码,如在其他地方调用则不会有任何输出。

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读