与 ACF 关系的相关帖子的输出 the_field

output the_field of related posts with ACF Relationship

首先,感谢您的帮助。

我必须按照代码显示相关的 post 从一个自定义 post 类型到另一个具有 ACF 关系的类型。

我想知道的是,是否有可能以及如何重写代码,以输出我在关系字段中选择的相关 post 的任何自定义字段?

<?php 
$posts = get_field('product_id');

    if( $posts ): ?>
        <ul>
        <?php foreach( $posts as $p ): ?>
            <li>
                <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>
            </li>
        <?php endforeach; ?>
        </ul>
  <?php endif; ?>

就像我在这里所做的那样,是:

echo get_permalink( $p->ID );

我要回显:

the_field('field_name')

此致, 阿克塞尔

如果您查看 the_field() 函数的文档,您会注意到它可以将 post/page ID 作为第二个参数,因此您可以检索特定 [=21] 的字段值=] 字段:

Parameters

the_field($selector, [$post_id], [$format_value]);

  • $selector (string) (Required) The field name or field key.
  • $post_id (mixed) (Optional) The post ID where the value is saved. Defaults to the current post.
  • $format_value (bool) (Optional) Whether to apply formatting logic. Defaults to true.

因此,例如:

<?php
$posts = get_field('product_id');

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $p ): ?>
        <li>
            <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>

            <?php the_field('field_name', $p->ID); ?>
        </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>