构建处理ajax请求的PHP脚本,并将ajax请求直接发送到该文件(而不是wp admin/admin ajax.PHP)。在该文件中,首先定义SHORTINIT
, 然后手动加载WordPress,最后处理ajax请求。
define(\'SHORTINIT\',true);
//IMPORTANT: Change with the correct path to wp-load.php in your installation
require_once (\'../../../../wp-load.php\');
//Load any WordPress module you may need from the include folder
//For exmaple:
//require( ABSPATH . WPINC . \'/meta.php\' );
//require( ABSPATH . WPINC . \'/post.php\' );
muestraMensaje();
function muestraMensaje(){
echo "hola que tal";
die();
}
假设您已将该文件命名为ajax。它位于URL mysite中。com/wp-content/plugins/a-plugin/ajax。php。javascript应该类似于:
$.ajax({
url: "http://mysite.com/wp-content/plugins/a-plugin/ajax.php",
})
.done(function( data ) {
alert(data);
});
在下一个示例中,我使用以下WordPress函数:
upadate_post_meta
,
get_post_custom
,
wp_send_json_success
和
wp_send_json_error
. 需要以下模块:
加载。php:始终需要加载WordPress格式。php:它包含用于upadate_post_meta
李>
元。php:它包含与post元数据和自定义字段相关的函数。php和修订版。php:这些模块包含更新post数据时所需的post相关函数这是PHP脚本:define(\'SHORTINIT\', true);
//IMPORTANT: Change with the correct path to wp-load.php in your installation
require( \'../../../wp-load.php\' );
require( ABSPATH . WPINC . \'/formatting.php\' );
require( ABSPATH . WPINC . \'/meta.php\' );
require( ABSPATH . WPINC . \'/post.php\' );
require( ABSPATH . WPINC . \'/revision.php\' );
cyb_uptdate_hits();
function cyb_uptdate_hits(){
if( isset($_GET[\'postID\']) ) {
$post_id = intval( $_GET[\'postID\']);
if( $post_id > 0 ) {
$get_meta = get_post_custom($post_id);
if( isset($get_meta[\'hits\'][0]) ) {
$prev = intval($get_meta[\'hits\'][0]);
} else {
$prev = 0;
}
update_post_meta($post_id, \'hits\', $prev + 1);
$res = array(\'postID\' => $post_id, \'hits\' => $prev + 1);
wp_send_json_success($res);
} else {
wp_send_json_error(\'No post to update.\');
}
} else {
wp_send_json_error(\'No post to update.\');
}
die(\'You die!\');
}
这是我正在使用的javascript:(function($){
$(document).ready(function(){
//Update post hits counter
if( typeof cyb_hits_data.postID !== \'undefined\' && cyb_hits_data.postID != "0") {
var update_hits = function(post_id){
$.getJSON(cyb_hits_data.ajax_url,{
postID : post_id
});
}
update_hits(cyb_hits_data.postID);
}
});
})(jQuery);
以及排队javascript:add_action( \'wp_enqueue_scripts\', \'cyb_hits_enqueue_scripts\' );
function cyb_hits_enqueue_scripts() {
wp_register_script(\'cyb-hits\', plugins_url( \'/js/hits.js\', __FILE__ ), array( \'jquery\' ) );
wp_enqueue_script(\'jquery\');
wp_enqueue_script(\'cyb-hits\');
$theID = 0;
if(is_single()) {
$theID = get_the_ID();
}
$scriptData = array(
\'ajax_url\' => plugins_url( \'/ajax_hits.php\', __FILE__ ),
\'postID\' => $theID
);
wp_localize_script(\'cyb-hits\',\'cyb_hits_data\',$scriptData);
}