首先,您应该始终使用WordPress AJAX方法,而不是用于此的自定义函数。看见AJAX in Plugins 在法典中。
考虑到这种做法,您可以这样设置您的请求。将AJAX URL更改为
<?php echo admin_url(\'admin-ajax.php\'); ?>
并添加
\'action\':
输入特定WordPress函数名的值,当服务器端接收到您的数据时,您希望在下一步中执行该函数名。
$(".post_thumbnail").click(function () {
var id_post = $(this).attr(\'post_id\');
$.ajax({
type: \'POST\',
url: \'<?php echo admin_url(\'admin-ajax.php\'); ?>\',
data: {
\'post_id\': id_post,
\'action\': \'f711_get_post_content\' //this is the name of the AJAX method called in WordPress
}, success: function (result) {
alert(result);
},
error: function () {
alert("error");
}
});
});
现在我们需要告诉WordPress当有人打电话时该怎么办
f711_get_post_content
.
在WordPress AJAX中注册操作。这是在Pluginfunctions中完成的。第一部分(“wp\\u ajax\\u”)是告诉WordPress这是一个ajax操作,然后是操作的名称(“f711\\u get\\u post\\u content”)。第二个参数是调用此操作时WordPress执行的函数。
add_action( \'wp_ajax_f711_get_post_content\', \'f711_get_post_content_callback\' );
// If you want not logged in users to be allowed to use this function as well, register it again with this function:
add_action( \'wp_ajax_nopriv_f711_get_post_content\', \'f711_get_post_content_callback\' );
然后创建回调函数。
Remember to ALWAYS die() your AJAX functions. 如果您的函数输出JSON,我建议您使用
wp_send_json( $array );
, 已内置
die()
.
function f711_get_post_content_callback() {
// retrieve post_id, and sanitize it to enhance security
$post_id = intval($_POST[\'post_id\'] );
// Check if the input was a valid integer
if ( $post_id == 0 ) {
echo "Invalid Input";
die();
}
// get the post
$thispost = get_post( $post_id );
// check if post exists
if ( !is_object( $thispost ) ) {
echo \'There is no post with the ID \' . $post_id;
die();
}
echo $thispost->post_content; //Maybe you want to echo wpautop( $thispost->post_content );
die();
}
这将是推荐的JSON版本。它允许您将多个变量传递回客户端。
function f711_get_post_content_callback() {
// retrieve post_id, and sanitize it to enhance security
$post_id = intval($_POST[\'post_id\'] );
// Check if the input was a valid integer
if ( $post_id == 0 ) {
$response[\'error\'] = \'true\';
$response[\'result\'] = \'Invalid Input\';
} else {
// get the post
$thispost = get_post( $post_id );
// check if post exists
if ( !is_object( $thispost ) ) {
$response[\'error\'] = \'true\';
$response[\'result\'] = \'There is no post with the ID \' . $post_id;
} else {
$response[\'error\'] = \'false\';
$response[\'result\'] = wpautop( $thispost->post_content );
}
}
wp_send_json( $response );
}