因此,我试图在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)
完成后,如果数据=ok,则函数echo为“ok”重新加载页面。由于某种原因,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
});
});
SO网友:Michal Mau
至于您的PHP没有被执行action
JavaScript AJAX调用中的参数需要与add_action
呼叫请看下面的示例。我还没有测试过,但应该可以。我已经简化了AJAX调用,可以根据您的用例随意修改它。
var data = {
action: \'jk-author-follow\', // Look Ma\' I talk to your PHP! :)
// ...
// here you can add any other custom vars you need to pass to the PHP handler
};
$.post(ajax_var.url, data, function(response){
if( typeof(console) == \'object\' ) console.log( response );
});
要记住的另一件事是执行PHP函数的上下文。它作为一个单独的请求运行,因此它不知道当前循环等。您可能需要传递其他变量(即。
user_id
) 在您的
data
对象
作为旁注-nopriv
适用于以下用户的钩子运行的变体not logged in. 如果您打算将您的功能专门用于登录用户,那么您最好放弃它。
有很多有用的信息Highest Voted \'ajax\' Questions 这里是WPSE。你也可以看看我以前对一个相关问题的回答:Adding callback function for wp_ajax_ has no effect. 这里提到的大多数信息也将与您相关。