0

Hi,

I created a custom post type called "news" and custom categories called "news_category" to have them categorized. I want to list "news" posts that belong to one of these categories. In this case the category id is 83. This is my code:

<?php
$news = get_posts( array(
    'post_type'      => 'news',
    'category' => 83
) );
 
if ( $news ) {
    foreach ( $news as $post ) {
        setup_postdata( $post );
        the_title();
    }
    wp_reset_postdata();
}
?>

This will produce nothing despite category ID is correct. If I use a 0 instead then it lists all posts regardless of their category but any other number will list nothing. Why is that?

By the way, I created the new taxonomy with this plugin: Custom post types

Thank you.

EDIT:

              <?php
    $news = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type' => 'news',
        'tax_query' => array(
                'taxonomy' => 'news_category',
                'field' => 'term_id',
                'terms' => 82,
            ),
        )
); 
    $postslist = get_posts( $news );    
    foreach ($postslist as $crap) {?>
         <a href="<?php $crap->title; ?>"><?php $crap->title; ?></a>
      <?php }?>
3
0

I'm assuming 'news_category' is a custom taxonomy; if not, and if you have simply created a new post category called 'news_category', it will only work if you add support to your custom post type. Be aware though that this will add complexities to your feeds and queries, as well as affecting how category posts show in the admin. It is most straightforward to do this with a custom taxonomy if you can.

Onto solving this using a custom taxonomy: You need to add a taxonomy query to your arguments, so WP knows where to look for that new term.

$news = get_posts(
    array(
        'post_type' => 'news',
        'tax_query' => array(
            array(
                'taxonomy' => 'nameofyourcustomtaxonomy',
                'field'    => 'slug',
                'terms'    => 'news_category',
            ),
        )
    )
);
1
  • sorry but its not working. Please refer to my edited question.
    – Cain Nuke
    Aug 13 '20 at 18:57

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