正确的答案是以正确的方式使用AJAX。
将脚本排队并本地化以将路径添加到admin-ajax.php
:
function wpd209588(){
wp_enqueue_script(
\'wpd209588_script\',
get_template_directory_uri() . \'/js/your-script.js?ver=1.0\',
array( \'jquery\' )
);
wp_localize_script(
\'wpd209588_script\',
\'WPaAjax\',
array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' )
)
);
}
add_action( \'wp_enqueue_scripts\', \'wpd209588_scripts\' );
在中
your-script.js
, 执行AJAX调用:
jQuery(document).ready(function($){
$.post(
WPaAjax.ajaxurl,
{
action : \'wpd209588_ajax\'
},
function( response ){
$( \'.container\' ).html( response );
}
);
});
将AJAX处理程序映射到AJAX脚本中调用的操作:
function wpd209588_ajax_function(){
global $wp_query;
$args = array(
\'posts_per_page\' => -1
);
$wp_query = new WP_Query( $args );
while ( have_posts() ) : the_post();
echo \'<li>\';
the_title();
echo \'</li>\';
endwhile;
exit;
}
add_action( \'wp_ajax_wpd209588_ajax\', \'wpd209588_ajax_function\' );
add_action( \'wp_ajax_nopriv_wpd209588_ajax\', \'wpd209588_ajax_function\' );