如何在 WP_Query 循环中使用 'post_type' => 'product' 显示 ACF

Sjo*_*erd 1 wordpress advanced-custom-fields

尝试实现这一目标:我在 WooCommerce 产品中创建了一个 ACF(自定义字段),现在我尝试使用以下代码在我的模板中显示该字段:

 <ul class="products">
    <?php

    $args = array(
        'posts_per_page' => 20,
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'name',
                'terms'    => 'grouped',
            ),
        ),
    );
    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();
            $linked_with_items = the_field('linked_with_items');
            the_title('<strong>', '</strong>'); echo '<br />';
            echo $linked_with_items;
        endwhile;
    } else {
        echo __( 'No products found' );
    }
    wp_reset_postdata();
    ?>
</ul><!--/.products-->
Run Code Online (Sandbox Code Playgroud)

但无论我尝试使用 get_field() ,该字段都不会显示在我的模板中。有人可以帮忙吗? https://www.advancedcustomfields.com/

这是最终代码仅供参考

 <?php if( have_rows('catalogue') ): ?>
   <?php
       while( have_rows('catalogue') ): the_row(); // catalogue is the field
       the_sub_field('linked_with_items'); ?>
 <?php endwhile; ?>
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

Die*_*ego 5

你可以尝试用这个:

$linked_with_items  = get_field('linked_with_items', get_the_ID());
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,就像测试一样,您可以尝试使用 foreach 简单地循环帖子

foreach ( $loop->posts as $post ) {
    $linked_with_items  = get_field('linked_with_items', $post->ID);
}
Run Code Online (Sandbox Code Playgroud)

如果这些都不起作用,请确保您的产品确实具有该自定义字段,仔细检查 ACF 字段设置(规则部分)、字段标题,并仔细检查您的产品编辑页面以查看这些字段是否显示在那里。