1
votes

I'm using the ACF relationship field to display related blog posts on each product. Currently it works but I have to check each product manually to show a related post on it.

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

Adding productsenter image description here

Issue: How could I add product categories instead so I wouldn't need to add manually 200 products but only one product category that has this post as related and will show the post under single view.

Possible solution?

Can this be integrated with the taxonomy ACF field instead (if post has taxonomy product_cat as related it will show under products in that category)? Unfortunately unable to think of a way

1

1 Answers

0
votes
<?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 ?>

try this code, place this code in single product page