通过chatGpt获取的结果
写一个WordPress功能,并列出代码,功能要求如下:
1、用户可以关注当前分类 使用ajax技术
代码:
// 为当前分类添加关注按钮
<?php
$category_id = get_query_var('cat');
echo '<div id="category-follow-button-'.$category_id.'">';
if(is_user_logged_in()){
$current_user_id = get_current_user_id();
if(check_category_follow($category_id, $current_user_id)){
echo '<input type="button" class="btn btn-primary" value="取消关注" onclick="category_unfollow('.$category_id.');"/>';
}else{
echo '<input type="button" class="btn btn-primary" value="关注" onclick="category_follow('.$category_id.');"/>';
}
}else{
echo '<input type="button" class="btn btn-primary" value="关注" onclick="alert("请先登录");"/>';
}
echo '</div>';
?>
// 前台js
<script>
function category_follow(category_id){
jQuery.ajax({
type: "POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: "follow_category", category_id: category_id },
success: function(data) {
if(data.status == 'success'){
jQuery('#category-follow-button-'+category_id).html('<input type="button" class="btn btn-primary" value="取消关注" onclick="category_unfollow('+category_id+');"/>');
}
}
});
}
function category_unfollow(category_id){
jQuery.ajax({
type: "POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: "unfollow_category", category_id: category_id },
success: function(data) {
if(data.status == 'success'){
jQuery('#category-follow-button-'+category_id).html('<input type="button" class="btn btn-primary" value="关注" onclick="category_follow('+category_id+');"/>');
}
}
});
}
</script>
// 后台php
<?php
// 检查用户是否关注当前分类
function check_category_follow($category_id, $user_id){
// 这里要检查数据库,是否存在指定的分类id和用户id
// 省略
return true;
}
// 关注当前分类
add_action('wp_ajax_nopriv_follow_category', 'follow_category');
add_action('wp_ajax_follow_category', 'follow_category');
function follow_category(){
$category_id = $_POST['category_id'];
$user_id = get_current_user_id();
// 这里要插入数据库,添加指定的分类id和用户id
// 省略
$data = array('status'=>'success');
wp_send_json($data);
}
// 取消关注当前分类
add_action('wp_ajax_nopriv_unfollow_category', 'unfollow_category');
add_action('wp_ajax_unfollow_category', 'unfollow_category');
function unfollow_category(){
$category_id = $_POST['category_id'];
$user_id = get_current_user_id();
// 这里要从数据库删除指定的分类id和用户id
// 省略
$data = array('status'=>'success');
wp_send_json($data);
}
?>