我想使用高级海关字段将公司与产品联系起来。这些是我网站上的一些页面:
www.example.com/companies/apple/
www.example.com/companies/microsoft/
www.example.com/products/iphones/
www.example.com/products/ipods/
例如,我想将苹果与他们的产品(iPhone和iPod)联系起来。
我在 ACF 中添加了一个称为 related_articles
的关系字段,该字段仅在页面父级为/companies/-page 时才可用。
所以在苹果的公司页面上——iPhone和iPod的产品已经在自定义关系字段中选择了related_articles
。
在页面上.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>
。我该如何解决这个问题?是否可以使用两种方式兼容的代码?
我不希望从产品到公司建立第二次"连接"——这需要从一页而不是两页处理。自定义帖子类型也是不行的。
已更新 - 查询关系字段文档中的新代码:
<?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; ?>
这剂量不会返回任何内容(空白)。
这当然是可能的 - ACF 允许对相关项目进行 2 路或反向查询。因此,您的产品页面,您可以执行以下操作(使用您自己的相关 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/
虽然,这是否可以不使用自定义帖子类型,但我不确定。