干净的解决方案是使用 WordPress AJAX 函数。
如今,主题通常被分成多个部分,以便在不同的地方重复使用块。例如,主题二十六在single.php 中使用get_template_part( 'template-parts/content', 'single' ); 来包含显示文件实际内容的模板文件。您可以轻松地使用它来获取帖子的内容,而无需页眉、页脚等。
首先,设置 PHP 部分,您可以将其添加到主题的 functions.php 中,也可以直接添加到插件中,具体取决于您正在开发的内容。
<?php
// for the admin area
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// for the public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
$postid = intval( $_POST['postid'] );
$post = get_post( $postid );
setup_postdata( $post );
get_template_part( 'template-parts/content', 'single' );
wp_die(); // this is required to terminate immediately and return a proper response
}
对应的JavaScript部分:
var data = {
'action': 'my_action',
'postid': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
// on the frontend you have to set it yourself
var ajaxurl = '<?=admin_url( 'admin-ajax.php' )?>';
jQuery.post(ajaxurl, data, function(response) {
// alert('Got this from the server: ' + response);
// response will now contain your post, without header, footer, sidebars etc.
});
my_action是整个流程的标识,两部分要一致。
WordPress AJAX 支持文档:https://codex.wordpress.org/AJAX_in_Plugins