WP_Query get posts from custom posts by category

ive been playing around with this for ages and for some reason I cant get it to work.

This is from within the single post page of a custom post type…

Read More

Basically I am getting the category of the custom post type by using the get_the_term and then doing a foreach to nicely input into a string.

I then use a WP_Query to retrieve, but I think I have the logic wrong.

This is what I have

// post types query
if ( have_posts() ) : while ( have_posts() ) :the_post();

// getting the categories
$categorynames = '';
$getcategory = get_the_terms($post->ID, 'custompostnamehere-categories');

foreach($getcategory as $t){ $categorynames .= $t->term_id.' ,';}

if (substr($categorynames, -1) == ',') {
$categorynames = substr($categorynames, 0, -1);
}

// end of post type query
endwhile; endif; wp_reset_query(); 

//starting new query to get related posts within the same categories
$args = array(
  'post_type' => 'custompostnamehere',
  'cat' => $categorynames,
  'posts_per_page' => 20
);
$q = new WP_Query($args);

// retrieving the data
while($q->have_posts()){

}

Could someone please enlighten me on my wrong doings.

Thanks

Related posts

1 comment

  1. You’re using category query for your custom taxonomy. So it won’t work, because there are no categories with such IDs.

    You should use tax_query instead.

    // post types query
    while ( have_posts() ) {
        the_post();
    
        // getting the categories
        $categoryIDs = array();  // it's much nicer than concatenated string
        $getcategory = get_the_terms($post->ID, 'custompostnamehere-categories');
    
        foreach($getcategory as $t) {
            $categoryIDs[] = $t->term_id;
        }
    
    // end of post type query
    }
    // resetting query isn't needed - you will call your own query next
    
    //starting new query to get related posts within the same categories
    $args = array(
        'post_type' => 'custompostnamehere',
        'tax_query' => array(
            array( 
                'taxonomy' => 'yourcustomtaxonomy',
                'field' => 'id',
                'terms' => $categoryIDs
            )
        ),
        'posts_per_page' => 20
    );
    $q = new WP_Query($args);
    
    // retrieving the data
    while( $q->have_posts() ) {
        $q->the_post();
        ...
    }
    

Comments are closed.