在 WordPress 中加载模板而不回显它

Posted

技术标签:

【中文标题】在 WordPress 中加载模板而不回显它【英文标题】:Load template in WordPress without echo it 【发布时间】:2013-09-28 05:47:09 【问题描述】:

我正在尝试编写一个自定义函数,以在单独的 div 中加载一组产品,以便在选项卡中使用。每个选项卡都有类别的名称,每个选项卡内容都包含产品。

我正在尝试使用 woocommerce 模板在循环中显示产品,但它会立即触发回声,从而破坏了设计。我需要将结果接收到输出参数中,并在最后回显。

我的代码在循环分类后(foreach as $prod_cat)如下所示:

$args = array(
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'tag_ID',
            'terms' => $prod_cat['id']
        )
    ),
    'order' => 'ASC'
);

$my_query = null;
$my_query = new WP_Query($args);
$counter = 0;
if ($my_query->post_count) 
    $output .= '<ul class="products">';

    if ($my_query->have_posts()) 
        while ($my_query->have_posts()) : $my_query->the_post();

            setup_postdata($post);

            $output .= woocommerce_get_template_part('content', 'product');

        endwhile;
    
    $output .= '</ul>';

所以它实际工作并且可以很好地加载产品,但是由于“woocommerce_get_template_part”调用“load_template”,它会回显文件内容。我希望它返回 $output 没有任何回声。这可能吗?

谢谢

【问题讨论】:

查看 woocommerce_get_template() 中是否定义了动作。例如do_action('woocommerce_get_template_part', 参数...)。如果是,则通过操作更改对函数的直接调用。 感谢您的回复。自从@Hobo 提供的解决方案有效以来,我还没有尝试过,但我非常感谢您的帮助。 【参考方案1】:

如果我正确理解了这个问题,您应该可以使用 php 的output buffering functionality 来解决这个问题。像这样的东西(未经测试):

while ($my_query->have_posts()) : $my_query->the_post();
    setup_postdata($post);
    ob_start(); // Start buffering
    woocommerce_get_template_part('content', 'product');
    $output .= ob_get_clean(); // Get the content of the buffer, and end buffering
endwhile;

【讨论】:

以上是关于在 WordPress 中加载模板而不回显它的主要内容,如果未能解决你的问题,请参考以下文章

php 通过代码在WordPress中创建一个新的管理员用户。将此文件放在mu-plugins目录中并更新变量,然后在Wor中加载页面

在 Freemarker 模板中加载模板而不为模板加载设置目录或类

PHP - 读取另一个 PHP 文件的内容而不回显

如何在 webpack 中加载 Pug 模板而不编译为 HTML?

AT&T 组装屏蔽输入

为啥我不能指定环境变量并在同一命令行中回显它?