在没有 get_header() 和 get_footer() 的情况下加载 Wordpress post

Load Wordpress post without get_header() and get_footer()

我正在开发一个 wordpress 网站,其中 post 被加载到带有 ajax(带有 Magnific Popup)的弹出窗口中。 post 正在使用模板 single.php

这工作正常,除了页眉和页脚也加载到弹出窗口中(html 标签、导航、脚本等)。我当然可以从模板中删除 get_header()get_footer(),但是单个 post 页面无法通过永久链接正确加载。

我尝试了条件标签,但是当模板加载 Ajax 时,它没有 'see' 它加载到主页上。

我认为使用不同的模板是一种选择,尽管我见过使用相同模板的网站(例如 themeforest 上的 Zoo 主题)。但是我不知道它在那里是如何工作的。

所以我被困在这里了。有人吗?

干净的解决方案是使用 WordPress AJAX 功能。

如今,主题通常分为多个部分,以便在各个地方重复使用块。例如,主题 twentysixteen 在 single.php 中使用 get_template_part( 'template-parts/content', 'single' ); 来包含显示文件实际内容的模板文件。您可以轻松地使用它来获取 post 的内容,而无需页眉、页脚等

首先,设置 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 插件中:"To modify content after it’s loaded, or to select and show just specific element from loaded file, there is a parseAjax callback"。

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