Blog

Display Related Post or Product based on Taxonomy in WordPress

Related post display in for custom post type is very easy. But if you have a custom taxonomy it is little tricky. You can use the following code to display related post from a post type. This code very useful to display related product while you are using custom taxonomy.

<?php
            // get the custom post type's taxonomy terms
            $custom_taxterms = wp_get_object_terms( $post->ID, 'product_category', array('fields' => 'ids') );
            // arguments
            $args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => 4, // you may edit this number
            'orderby' => 'rand',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_category',
                    'field' => 'id',
                    'terms' => $custom_taxterms
                )
            ),
            'post__not_in' => array ($post->ID),
            );
            $related_items = new WP_Query( $args );
            // loop over query
            if ($related_items->have_posts()) :
            while ( $related_items->have_posts() ) : $related_items->the_post();
            ?>
            <div class="related_item">
              <div class="Related_image">
                <a href="<?php the_permalink() ?>"><?php echo get_the_post_thumbnail( ); ?></a>
              </div>
                <div class="Related_title">
                  <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><h2>
                   
                </div>
              </div>
            <?php
            endwhile;
            endif;
            // Reset Post Data
            wp_reset_postdata();
            ?>

In This post my Taxony name is product_category and post type name is product

Don’t forget to change this two variable as per your name.  My result of code.