首页 > 解决方案 > Woocommerce 产品类别帖子的 ACF 关系字段

问题描述

我正在使用 ACF 关系字段来显示每个产品的相关博客文章。目前它可以工作,但我必须手动检查每个产品才能在其上显示相关帖子。

$posts = get_posts(array(
        'meta_query' => array(
            array(
                'key' => 'products', // name of custom field
                'value' => '"' . $product->get_id() . '"',
                'compare' => 'LIKE'
            )
        )
    ));

添加产品在此处输入图像描述

问题: 我怎样才能添加产品类别,这样我就不需要手动添加 200 个产品,而只需添加一个与此帖子相关的产品类别,并将在单个视图下显示该帖子。

Possible solution?

这是否可以与分类 ACF 字段集成(如果帖子具有相关的分类 product_cat,它将显示在该类别的产品下)?可惜想不出办法

标签: phpwordpressadvanced-custom-fields

解决方案


<?php
global $post;

//Related Product Section Start

$term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "ids", "parent" => 0 ));
$term_name = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "names", "parent" => 0));

if ( $term_list ) { 
    $data_related = new WP_Query 
        ( 
            array (
                'post_type' => 'your_post_type',
                'posts_per_page' => -1,
                'post__not_in' => array( $post->ID ),
                'post_status' => 'publish',
                'tax_query' => array(
                    array (
                        'taxonomy' => 'your_taxonomy',
                        'field' => 'term_id',
                        'terms'    => $term_list[0],
                    ),
                ),
            ) 
        );

    if ( $data_related->have_posts() ) { ?>
        <div class="product-part">
            <div class="container">
                <h2><?php echo $term_name[0]; ?></h2>
                <?php  while ( $data_related->have_posts() ) {
                    $data_related->the_post();  
                    echo '<div class="col-12  col-md-6 col-lg-4 col-xl-4">' .
                            '<h6>' . get_the_title( get_the_ID() ) . '</h6>' .
                    '</div>';
                } ?>
             </div>        
        </div>
    <?php } wp_reset_query(); wp_reset_postdata();
} 

//Related Product Section End ?>

试试这个代码,把这个代码放在单个产品页面中


推荐阅读