加载不带get_header()和get_footer()的Wordpress文章


Load Wordpress post without get_header() and get_footer()

我正在开发一个wordpress网站,在这个网站上,帖子用ajax(使用Magnific popup(加载到弹出窗口中。帖子使用模板single.php

这很好,只是页眉和页脚也加载在弹出窗口中(html标记、导航、脚本…(。我当然可以从模板中删除get_header()get_footer(),但随后单个帖子页面无法通过永久链接正确加载。

我尝试了条件标记,但当用Ajax加载模板时,它不会"看到"主页上加载了它。

我认为使用不同的模板是一种选择,尽管我见过使用相同模板的网站(比如之前的动物园主题(。但我不知道它是如何在那里工作的。

所以我被困在这里了。任何人

干净的解决方案是使用WordPress AJAX函数。

如今,主题通常被拆分为多个部分,以便在不同的地方重用块。例如,主题twentysixten使用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

我终于发现这个选项包含在Magnific Popup插件中:"要在加载后修改内容,或者从加载的文件中选择并显示特定元素,有一个parseAjax回调"。

但我会接受上面的答案,因为我认为这是一种优雅的方式,而不是加载整个页面,只显示所需的部分。