好的,我不知道该如何命名这个主题。
我试图用ajax覆盖默认行为。这里的问题实际上不是一个问题,而是一个更大的愿望。
我有以下url:
<a href="http://example.com/?reaction=smk_remove_post&id=1226&_nonce=7be82cd4a0" class="smk-remove-post">Remove post</a>
在functions.php
我有此功能,并在以下时间后立即调用:function smk_remove_post(){
if( !empty( $_GET[\'reaction\'] ) && \'smk_remove_post\' == $_GET[\'reaction\'] && !empty( $_GET[\'id\'] ) ){
if( current_user_can(\'edit_others_posts\') && !empty($_GET[\'_nonce\']) ){
if( wp_verify_nonce( esc_html( $_GET[\'_nonce\'] ), \'smk_remove_post\' ) ){
// Delete the post
wp_delete_post( absint( $_GET[\'id\'] ), true );
}
}
}
}
smk_remove_post();
现在如果我点击ID为的帖子链接1226
将被删除。一切正常。任务成功完成,页面重新加载。这就是我需要AJAX的地方。我想使用ajax处理此URL,而不是重新加载页面,and get a proper response.
我添加了以下jQuery脚本:
function smk_remove_post(){
$(\'.smk-remove-post\').on( \'click\', function( event ){
event.preventDefault();
var _this = $(this);
jQuery.ajax({
type: "GET",
url: _this.attr(\'href\'),
success: function(response){
console.log(response);
_this.text(\'All great, the post is removed.\');
}
});
});
}
smk_remove_post();
一切正常。该帖子通过ajax删除,无需重新加载页面。但我无法得到正确的响应,而是得到了当前页面的完整HTML源代码。我知道我应该使用admin-ajax.php
(ajaxurl),但我该怎么做呢?我需要从URL发送查询并获得回复。
Here is what I\'ve tryied:
我已将此添加到上面的jQuery脚本中:data: {
\'action\': \'smk_remove_post_ajax\',
},
这就是PHP:function smk_remove_post_ajax(){
smk_remove_post();
die();
}
add_action(\'wp_ajax_smk_remove_post_ajax\', \'smk_remove_post_ajax\');
它不起作用。它被忽略了,前面的调用被替代执行,就像这将在没有ajax的情况下完成一样。我知道我需要以某种方式将查询发送给admin ajax。php,但如何?