使用插件替换主 WP 循环

Replace Main WP Loop Using Plugin

我想用其他文件中的代码替换主 WP 循环,例如:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'tpl/content', 'single' ); ?>
<?php endwhile;
    endif;?>  

类似于 Woocommerce 中的东西 - 我只想替换网站的 "content",网站的页眉和页脚应该看起来像主题。 我试过使用 "template_include" 和 "single_template" 但这些方法正在替换整个页面。

我的主要目标是使用我的插件替换 "content",无论 WP 中使用什么主题。

My main target is to replace "content" using my plugin, no matter what theme is used in WP.

如果您想更改 wordpress 页面的 "content",您应该考虑

  1. 编写函数并将该函数添加到内容过滤器 the_content,或
  2. 创建简码,让用户选择在哪个页面上呈现您的插件内容。
    • 您还可以创建一个挂钩到 register_activation_hook 的函数,该函数创建一个新页面,其中预加载了您的插件的短代码。我很确定这就是 WooCommerce 所做的。

正在编写函数并将该函数添加到内容过滤器 the_content!

<?php
// one/of/your/plugin/files.php

function marcin_plugin_content($content) {
    /**
     * Some check to establish that the request is for
     * a page that your plugin is responsible for altering.
     */
    if (true === is_page('marcin_plugin_page')) {
        $new_content = 'whatever it is you do to create your plugin\'s content, do it here!';
        return $new_content;
    }

    // we don't want to alter content on regular posts/pages
    return $content;
}

add_filter('the_content', 'marcin_plugin_content');

https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content

创建简码,让用户选择在哪个页面上呈现您的插件内容。

<?php
// one/of/your/plugin/files.php

function marcin_plugin_shortcode($atts)
{
    // Borrowed from https://codex.wordpress.org/Shortcode_API
    $a = shortcode_atts(
        [
         'foo' => 'something',
         'bar' => 'something else',
        ],
        $atts
    );

    // Do whatever you do here to generate your plugin's output...
    $output = 'Foo: "'.$a['foo'].'", Bar: "'.$a['bar'].'"';

    return $output;
}

add_shortcode('marcin', 'marcin_plugin_shortcode');

然后,您的用户将负责将 [marcin] 短代码放入页面或 post 以呈现插件的 "content".

如果您想为您的用户自动创建一个页面,您可以尝试:

<?php
// path/to/your/plugin/files.php

function marcin_on_activate() {
    // Maybe do a check that this doesn't exist already to avoid duplicates.. this is just an example!!
    $data = [
        'post_title'    => 'Plugin Page',
        'post_content'  => '[]',
        'post_status'   => 'publish',
    ];

    // Insert the post into the database.
    wp_insert_post($data);
}

register_activation_hook(__FILE__, 'marcin_on_activate');

我鼓励您阅读 WP 法典的 Plugin API 页,如果您还没有的话!另外,这样您就知道可以挂钩或过滤到的位置:

更多参考资料:

编辑:OP 写道:

My bad: "content" - i mean all fields of my CPT: for example: title, description, author, create date, price...number of rooms...etc.

在这种情况下,您需要覆盖模板,然后在模板中 do as WooCommerce does, and include calls to get_header() and get_footer()。那些函数

Include...the [header/footer].php template file from your current theme's directory.