Grab all the posts for particular category

enter image description here

So I have a class called Recipe and inside I have a get() method as shown below:

public function get()
{
    $taxonomies = get_terms([
        'taxonomy' => 'recipe-categories',
        'hide_empty' => false
    ]);

    $output = '';

    if (!empty($taxonomies)):

        $output = '<div>';
        foreach ($taxonomies as $category)
        {
            if ($category->parent == 0)
            {
                $output .= '<p><a href="' . get_home_url() . '/recipe-categories/' . esc_attr__($category->slug) . '">'. esc_attr__($category->name) .'</a></p>';
                foreach ($taxonomies as $subcategory) {
                    if ($subcategory->parent == $category->term_id) {
                        $output.= '<p>'. esc_attr($subcategory->term_id) . ' ' . esc_html($subcategory->name) .'</p>';
                    }
                }
            }
        }
        $output .= '<div>';
    endif;

    return $output;
}

This gives me all the categories in my custom post type:

If I click into one of the specific categories, it will lead me to a template that I’m using that will display the category posts:

'/recipe-categories/' . esc_attr__($category->slug)

Here is the code that I’m using inside the template:

<?php
get_header();
?>
    <div class="four-sixths first">
        <?php

        $args = [
            'category' => 'bread',
            'post_type' =>  'recipe'
        ];
        $postslist = get_posts($args);

        foreach ($postslist as $post) :  setup_postdata($post); ?>
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <?php the_excerpt(); ?>
        <?php endforeach; ?>
    </div>

    <div>
        <?php get_sidebar(); ?>
    </div>
    <div class="clearfix"></div>
<?php
get_footer();

I’ve added the 'category' => 'bread' slug for testing purposes and I’m getting all the posts particular to the bread category.

The real question is, how can I make it detect my category slug and pull in all posts that are linked to a particular category?

Read more here:: Grab all the posts for particular category

Leave a Reply

Your email address will not be published. Required fields are marked *