0

I have a custom post type with custom category taxonomy. On the CPT single templae I want to list out other posts in same categories, but I can't get it to work.

My current code:

<?php
foreach ( Roots\Sage\Utils\get_the_category_bytax( get_the_ID(), 'project_category' ) as $cat )
  $category_ids[] = $cat->term_id;

  $projects = new WP_Query( array(
    'post_status'      => 'publish',
    'post__in'         => get_post_meta( get_the_ID(), 'carbonlimits_project_related', true ),
    'post__not_in'     => array( $current_post_id ),
    'category__and'    => $category_ids,
    'post_type'        => 'project',
    'caller_get_posts' => 1,
    'posts_per_page'   => 4
  ) );

  while ( $projects->have_posts() ): $projects->the_post() ?>

    <div id="project-<?php the_ID() ?>" <?php post_class( 'col-sm-3' ) ?>>
      <a href="<?php the_permalink() ?>">
        <?php
        $thumbnail = get_the_post_thumbnail( get_the_ID(), 'project-listing' );
        if ( $thumbnail )
          echo $thumbnail;
        else
          echo '<img src="/wp-content/themes/carbonlimits/dist/images/blank.gif" width="380" height="380">';
        ?>
        <h3><?= $projects->post->post_title ?></h3>
        <span class="view-btn">View</span>
      </a>
    </div>

  <?php endwhile;
  // var_dump( $projects->request );
  wp_reset_postdata();
?>

Is it because it's a custom post type and taxonomy?

1

1 Answer 1

0

This should work for a custom taxonomy.

<?php
function get_related_posts() {

    global $post;

    $taxonomy = 'your_custom_taxonomy';
    $terms = wp_get_post_terms( $post->ID, $taxonomy );

    if($terms) {
        $term_arr = '';
        foreach( $terms as $term ) {
            $term_arr .= $term->slug . ','; // create array of term slugs
        }

        $args = array(
          'showposts' => 5, // you can change this to whatever you need
          'post__not_in' => array($post->ID) // exlude current post from results
          'tax_query' => array(
            array(
              'taxonomy' => $taxonomy,
              'field' => 'slug', // using 'slug' but can be either 'term_id', 'slug' or 'name'
              'terms' => $term_arr // array of ID values, slugs or names depending what 'field' is set to
            )
          )
        );
        $related_posts = get_posts( $args );

        if($related_posts) {

          foreach ( $related_posts as $post ) : setup_postdata( $post ); 
            // output whatever you want here
            the_title(); // for example
          endforeach;

        } else {

          echo 'No Related Posts';

        }

    }

    wp_reset_postdata();
}
?>
2
  • $term_arr in undefined :-) Commented Jun 16, 2015 at 8:55
  • Oops! Good catch :) Commented Jun 16, 2015 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.