为了详细说明Chris的回答,AJAX调用在您的函数中看起来像这样。php文件:
add_action(\'wp_ajax_add_favorite\', \'add_favorite\');
function add_favorite(){
$post_id = $_POST[\'postID\'];
$nonce = $_POST[\'nonce\'];
if(!wp_verify_nonce($nonce, \'wpnonce\'))
exit;
if($post_id):
$favorites = get_user_meta(get_current_user_id(), \'favorites\');
if(in_array($post_id, $favorites)):
$response = \'Already in favorites.\';
$success = false;
else:
if(add_user_meta(get_current_user_id(), \'favorites\', $post_id, false)):
$response = "This post was added to your favorites";
$success = true;
endif;
endif;
else:
$success = false;
$response = "No post ID was supplied";
endif;
$output = json_encode(array(\'success\'=>$success, \'response\'=>$response));
echo $output;
exit;
}
jQuery AJAX请求如下所示:
jQuery(\'.add-to-favorites\').click(function(){
var data = {
action: \'add_favorite\',
nonce: jQuery(\'#_wpnonce\').val(),
postID: jQuery(this).attr(\'rel\')
};
jQuery.post(ajaxurl, data, function(output) {
var obj = jQuery.parseJSON(output);
if(!obj.response) alert(\'Something went wrong with the server.\');
if(obj.success){
//Do Something Here
alert(obj.response);
}
else{
alert(obj.response);
}
});
//Disable Click Through
return false;
});
前端上的链接如下所示:
<a class="add-to-favorites\' rel="<?php echo $post->ID;?>" href="#">Add To Favorites</a>
在被调用的“wpnance”中添加一个隐藏的nonce字段,这应该很管用。此外,确保在前端定义了ajaxurl,以便脚本知道将请求发送到哪里。
不过,您需要在另一个PHP AJAX函数中执行一些反向工程,才能从收藏夹中删除。希望这对你有所帮助。