我已经搜索了很多次,但仍然没有找到任何解决方案。我想在提交帖子评论后调用ajax操作。我怎样才能用WordPress做到这一点?
发布于 2016-01-15 15:09:16
没有代码,我自己就不能给你下面的代码步骤:
wp-admin/admin-ajax.php发送请求并将逻辑放在functions.php下。添加die()函数。发布于 2016-01-15 16:40:09
我会用WordPress过滤器过滤评论。您可能根本不需要AJAX请求。但是我不太确定为什么你需要AJAX。To learn more about this filter.
function preprocess_comment_handler( $commentdata ) {
//some code
return $commentdata;
}
add_filter( 'preprocess_comment' , 'preprocess_comment_handler' );如果您确实需要AJAX,这里介绍如何让它在WordPress中运行。您需要使用wp_localize_script()将AJAX转到admin-ajax.php。
//add wp_localize_script to your functions.php
//make sure to enqueue the js file you are writing to and it's dependencies
function acarter_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script('your-script', get_template_directory_uri() . '/js/theme.js');
wp_localize_script('your-script', 'your_script_vars', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
add_action( 'wp_enqueue_scripts', 'acarter_enqueue_scripts' );
//do your AJAX call in the file you just enqueued
jQuery( document ).ready( function($) {
//Ajax Form Processing
var $form = $( '#button' )
$form.submit( function (e) {
e.preventDefault();
$.ajax({
type: '',
url: your_script_vars.ajaxurl,
data: {
action: 'function_name_of_the_callback',
//key : values of stuff you want in the php callback
},
dataType: 'json',
success: function (response) {
if ( true === response.success ) {
console.log( 'success!!' );
});
} else if ( false === response.success && response.data ) {
window.alert( 'doing it wrong' );
}
}
});
});
});您也许可以将数据发送到前面提到的过滤器,从而使用过滤器作为回调,但我从未尝试过这样做。至少,您将知道如何在WordPress中设置AJAX。
https://stackoverflow.com/questions/34804758
复制相似问题