Jimmylet
3/27/2019 - 1:03 PM

Related posts by categories for custom post type

<?php

        //get the taxonomy terms of custom post type
        $customTaxonomyTerms = wp_get_object_terms( $post->ID, 'category', ['fields' => 'ids'] );

        //query arguments
        $args = [
          'post_type' => 'customer',
          'post_status' => 'publish',
          'posts_per_page' => 3,
          'orderby' => 'rand',
          'tax_query' => [
            [
              'taxonomy' => 'category',
              'field' => 'id',
              'terms' => $customTaxonomyTerms
            ]
          ],
          'post__not_in' => [ $post->ID ],
					];

        //the query
        $relatedPosts = new WP_Query( $args ); ?>

        <!-- loop through query -->
				@if ($relatedPosts->have_posts())
					@while( $relatedPosts->have_posts() ) @php( $relatedPosts->the_post() )
						<?php the_title(); ?>
					@endwhile
				@else
				@endif

        <?php wp_reset_postdata(); ?>