因此,我试图在wp中创建一个follow按钮,但由于某些原因,ajax按钮不能正常工作。下面是应该发生的事情的步骤
用户单击followbtn,Ajax转到$\\u POST action,该操作=follow,php运行wp\\u set\\u object\\u terms($user\\u id,$author\\u id,\'follow\',true)
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
});
});