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

问题描述 投票:0回答:1

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

我正在尝试使用woocommerce模板在循环中显示产品,但它立即激发回声,这打破了设计。我需要将结果接收到输出参数中,并在结束时回显它。

循环类别后,我的代码(foreach为$ 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而没有任何回声。那可能吗 ?

谢谢

php wordpress include woocommerce require-once
1个回答
3
投票

如果我已经正确理解了这个问题,你应该可以用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;
© www.soinside.com 2019 - 2024. All rights reserved.