高级自定义字段关系 - 基本循环 + 反转?

Advanced Custom Fields Relationship - Basic loop + reversed?

我想使用高级海关字段连接 公司产品。这些是我网站上的一些页面:

www.example.com/companies/apple/
www.example.com/companies/microsoft/
www.example.com/products/iphones/
www.example.com/products/ipods/

例如,我想将 Apple 与其产品(iPhone 和 iPod)连接起来。

我在 ACF 中添加了一个名为 related_articles 的关系字段,该字段仅在父页面为 /companies/-page 时可用。

因此在 Apple 的公司页面上 - 在自定义关系字段中选择了产品 iPhone 和 iPod related_articles

在 page.php 我添加了以下内容:

<?php 

$posts = get_field('related_articles');

if( $posts ): ?>
    <?php foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT) ?>
            <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a><br>
    <?php endforeach; ?>
<?php endif; ?>

在页面 www.example.com/companies/apple/ 上 returned:

<a href="http://www.example.com/products/iphones/">iPhones</a><br>
<a href="http:// www.example.com/products/ipods/">iPods</a><br>

完全符合我的要求。

问题是 http://www.example.com/products/iphones/http:// www.example.com/products/ipods/ 是空的。这里我想把关系倒转,显示<a href="http://www.example.com/companies/apple/">Apple</a><br>。我该如何解决这个问题?是否有可能使用两种方式兼容的代码?

我不想做第二个 "connection",从产品到公司 - 这需要从一个页面而不是两个页面处理。自定义 post 类型也是不行的。

已更新 - 来自 Querying relationship fields 文档的新代码:

<?php 

$related_articles = get_posts(array(
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'related_articles', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));
?>

<?php if( $related_articles ): ?>
    <?php foreach( $related_articles as $article ): ?>
        <a href="<?php echo get_permalink( $article->ID ); ?>"> <?php echo get_the_title( $article->ID ); ?></a><br>
    <?php endforeach; ?>
<?php endif; ?>

这没有 return 任何东西(空白)。

这当然是可能的——ACF 允许对相关项进行双向或反向查询。因此,您的产品页面,您可以执行以下操作(使用您自己的相关 acf 名称)

global $post;
$related_company = get_posts(
    array(
        'post_type'=>'company',
        'meta_query'=>array(
            array(
                'key' => 'related_product',
                'value' => '"'.$post->ID.'"',
                'compare' => 'LIKE'
            )
        )
));

整个过程在ACF网站上有详细解释:http://www.advancedcustomfields.com/resources/querying-relationship-fields/

不过,如果不使用自定义 Post 类型,这是否可行,我不确定。