1

I have a custom post type called guides, there are 3 categories a post can be within, the 3 categories are child categories of a category with id 87.

Currently I can loop through these categories and display their name and/or ID. I need to loop through each category and display the posts in that category. I can't seem to figure out how. This is the code I have that loops through the categories and displays their ID. In this loop I would like to display the posts. How can I do this?

$categories = get_categories( array(
    'orderby' => 'name',
    'child_of'  => 87,
    'order'   => 'ASC'
) );

foreach( $categories as $category ) {
    echo $category->term_id;
}

1 Answer 1

1

Your start looks already ok. You now need to get the posts which have the term_id of your $category.

$categories = get_categories( array(
    'orderby' => 'name',
    'child_of'  => 87,
    'order'   => 'ASC'
) );

foreach( $categories as $category ) {

    // display current term name
    echo $category->name;

    // display current term description, if there is one
    echo $category->description;

    // get the current term_id, we use this later in the get_posts query
    $term_id = $category->term_id;

    $args = array(
        'post_type' => 'guides', // add our custom post type 
        'tax_query' => array(
            array(
                'taxonomy' => 'category', // the taxonomy we want to use (it seems you are using the default "category" )
                'field' => 'term_id', // we want to use "term_id" so we can insert the ID from above in the next line
                'terms' => $term_id // use the current term_id to display only posts with this term
            )
        )
    );
    $posts = get_posts( $args );

    foreach ($posts as $post) {

        // display post title
        echo $post->post_title;

        // display post excerpt
        echo $post->post_excerpt;

        // or maybe you want to show the content instead use ...
        #echo $post->post_content;

    }

}

As I pointed out, its not clear from your question if you are using the default "category" taxonomy of wordpress or a custom taxonomy.

As you can see this is just bare minimum code. So Iam sure you will need to extend it a little bit, for example adding permalinks to the post and stuff.

Also take a look at the codex regarding the get_posts() function. Here you get some info about taxonomy query´s with get_posts().

For all usable taxonomy parameters visit the wp_query() codex here.
Here you will see that in some cases (for example if a post is in multiple sub categories) you can also use an array of ID´s instead of a single term_id, like so:

'field'    => 'term_id',
'terms'    => array( 103, 115, 206 ),

Your Answer

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

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