我创建了一个“喜欢帖子”按钮,用户可以单击该按钮将帖子保存到他们的“喜欢”列表中。该按钮将当前帖子ID附加到user_meta字段。 但是当用户再次单击该按钮时,如何从user_meta数组和chris_likes值-1中删除帖子ID?
functions.php
<?php
add_action('wp_ajax_nopriv_chris_like_post', 'chris_like_post');
add_action('wp_ajax_chris_like_post', 'chris_like_post');
function chris_like_post(){
global $user_ID;
$postID = $_REQUEST['post'];
if( is_numeric( $postID ) ){
$count = get_post_meta($postID, 'chris_likes' , true);
if( empty($count) || $count == '' ) $count = 0;
$count++;
if ( $user_ID ) {
$user_liked = get_the_author_meta( 'liked', $user_ID );
$user_liked_posts = explode( ',' , $user_liked);
if( empty($user_liked) ){
update_user_meta( $user_ID, 'liked', $postID );
update_post_meta( $postID, 'chris_likes', $count );
}
else{
if( !in_array($postID , $user_liked_posts) ){
update_post_meta( $postID, 'chris_likes', $count );
$postID = $user_liked.','.$postID;
update_user_meta( $user_ID , 'liked' , $postID );
}
}
}else{
$user_liked = $_COOKIE["chris_likes_".$postID];
if( empty($user_liked) ){
setcookie( 'chris_likes_'.$postID , $postID , time()+999999 , '/');
update_post_meta( $postID, 'chris_likes', $count );
}
}
echo $count ;
}
die;
}
?>
页面模板
<?php
global $post ,$postID; $postID = $_REQUEST['post'];
$count = get_post_meta($post->ID, 'chris_likes', true);
$active = $liked = false ;
if ( $user_ID ) {
$user_liked = get_the_author_meta( 'liked' , $user_ID ) ;
$user_liked_posts = explode( ',' , $user_liked);
if( in_array( $post->ID , $user_liked_posts) ){
$active = ' active';
$liked = '';
}
else{
$active = '';
$liked = '';
}
}
else{
$user_liked = $_COOKIE["chris_likes_".$post->ID] ;
if( !empty($user_liked) ){
$active = ' active';
$liked = __( '' , 'chris');
}
}
?>
<div class="card-count">
<div class="like">
<a href="javascript:;" class="chris-likes<?php echo $active; ?> iconfont icon-seed-filled" rel="<?php echo $post->ID ?>" title="<?php echo $liked; ?>">
<span class="count-num"><?php if( empty($count) ) echo "0"; else echo $count; ?></span>
</a>
</div>
</div>
js
jQuery(document).ready(function() {
jQuery(document).on("click", "a.chris-likes",
function() {
var post_id = jQuery(this).attr('rel');
var like = jQuery(this);
var rateHolder = $(this).children('.count-num');
if (like.hasClass('active')) {
$.post("/wp-admin/admin-ajax.php", {
action: 'chris_like_post',
post: post_id
},
function(data) {
like.removeClass('active').attr('title', '');
$(rateHolder).html(data);
},
'html');
} else {
$.post("/wp-admin/admin-ajax.php", {
action: 'chris_like_post',
post: post_id
},
function(data) {
like.addClass('active').attr('title', '');
$(rateHolder).html(data);
},
'html');
}
});
});