首页 > 解决方案 > 分配给帖子的 Woocommerce 产品(使用 ACF 关系字段)以显示在该帖子中列出

问题描述

我创建了一个出现在 woocommerce 产品中的 ACF 关系字段。使用该关系字段,我将普通帖子分配给产品。

编辑:切换到ACF 关系字段

我正在尝试做的事情: 现在在前端查看帖子(而不是产品!)时,我尝试显示帖子分配到的产品中的所有产品标题。

使用 ACF 查询在产品详细信息页面中显示帖子没有问题。但我们需要它反过来。有没有办法在帖子单个模板中查询它。检查此帖子分配给哪些产品并显示标题?

感谢帮助

标签: wordpresswoocommerce

解决方案


解决方案:

在 single-post.php 模板中运行一个子查询:

<ul class="products">
<?php
$args = array(
'post_type'   => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,  // -1 will get all the product. Specify positive integer     value to get the number given number of product
    'meta_query'    =>  array(
    array(
        'key'     =>  'RELATIONSHIP_FIELD_SLUG',
        'value'   =>  $post_id,
        'compare' =>  'LIKE',
    ),
)
    );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) : $the_query->the_post();

    // Show the title
    the_title();

endwhile;
} else {
    echo __( 'No products found' );
}
wp_reset_postdata();
?>

推荐阅读