【发布时间】:2016-06-08 23:34:57
【问题描述】:
我想使用高级海关字段将 公司 与 产品 联系起来。这些是我网站上的一些页面:
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/返回以下内容:
<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>。我该如何解决这个问题?是否可以使用两种方式兼容的代码?
我不希望建立从产品到公司的第二次“联系”——这需要从一个页面而不是两个页面来处理。自定义帖子类型也不行。
更新 - 来自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; ?>
这不会返回任何东西(空白)。
【问题讨论】:
标签: php wordpress advanced-custom-fields