【问题标题】:How to show ACF in a WP_Query loop with 'post_type' => 'product'如何使用 'post_type' => 'product' 在 WP_Query 循环中显示 ACF
【发布时间】:2021-03-09 12:52:05
【问题描述】:

尝试实现这一点: 我在我的 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-->

但是无论我用 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; ?>

【问题讨论】:

  • 只是为了确认您已在您的产品帖子中为这个新字段设置了一个值,对吗? var_dump(get_field('linked_with_items')); 有什么用?
  • NULL 是我得到的响应

标签: wordpress advanced-custom-fields


【解决方案1】:

你可以试试这个:

$linked_with_items  = get_field('linked_with_items', get_the_ID());

如果这不起作用,只是作为测试,您可以尝试使用 foreach 简单地循环帖子

foreach ( $loop->posts as $post ) {
    $linked_with_items  = get_field('linked_with_items', $post->ID);
}

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

【讨论】:

  • 这两种方法都不起作用。我想我的循环做错了......因为这个循环在另一个循环内。我继续看
  • 请尝试 var_dump($post->ID);在第二个解决方案中,如果 acf_field 实际存在并保存,则在数据库中查找。或者反过来,找到一个确实保存了 acf_field 的帖子,然后使用硬编码(仅作为测试)来查看 get_field 是否适合您
  • 确实你会看到 int(304) int(270) int(193) int(19) int(13) int(6)
  • 好的,现在使用这些 id,搜索 wp_postmeta 表并查看其中是否有任何将“linked_with_items”作为具有实际值的 postmeta 行之一
  • 感谢我的想法朝着正确的方向发展! linked_with_items 不是字段,而是字段中的子字段,我很愚蠢
猜你喜欢
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多