所以我试图在wp中创建一个关注按钮,由于某种原因,ajax按钮无法正常工作。 以下是应该发生的步骤
由于某种原因,php没有执行,页面没有重新加载。
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
if($_POST['action'] == "follow") {
$author_id = get_the_author_meta( 'nickname' ); // get authors name
$termId = get_term_by( 'slug', $author_id, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$author_follow_count = count( $followers );
if ( is_user_logged_in() ) { // user is logged in
$user_id = get_current_user_id(); // current user
wp_set_object_terms( $user_id, $author_id, 'follow', true ); // Follow the author
echo "ok";
}
}
}
exit;
}
前端按钮
function getAuthorFollowLink( $author_id ) {
$author = get_the_author_meta( 'nickname' );
$user_ID = get_current_user_id();
$termId = get_term_by( 'slug', $author, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$count = count( $followers );
$output = '<a href="#" id="followbtn">Folllow '.$count.'</a>';
return $output;
}
JS
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: ajax_var.url,
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
location.reload();
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
答案 0 :(得分:0)
尝试停用此代码
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
如果你知道其含义。您可能想了解更多https://codex.wordpress.org/Function_Reference/wp_verify_nonce