I have created a custom post type in functions.php with this code.
function create_recipes() {
register_post_type('recipe', [
'public' => true,
'show_in_rest' => true,
'labels' => [
'name' => 'Recipes',
'add_new_item' => 'Add New Recipe',
'edit_item' => 'Edit Recipe',
'all_items' => 'All Recipes',
'singular_name' => 'Recipe',
],
'supports' => ['title', 'editor'],
'rewrite' => ['slug' => 'recipes'],
'menu_icon' => 'dashicons-media-archive',
'has_archive' => true,
'taxonomies' => array('category'),
'supports' => array( 'title', 'editor', 'author', 'thumbnail' ),
]);
}
add_action('init', 'create_recipes');
And now I am trying to get/show all the posts on my frontend that I’ve created that have different categories here
<?php
$recipes = new WP_Query(['post_type' => 'recipe', 'category' => '01']);
while ($recipes->have_posts()):
$recipes->the_post();
?>
<div class="sub-column">
<div class="sub-cat">
<?php the_category(); ?>
</div>
<a>
<div class="sub-thumbnail">
<?php echo the_post_thumbnail(); ?>
</div>
</a>
<div class="sub-title">
<h4><?php the_title(); ?></h4>
</div>
</div>
<?php endwhile;
?>
But I cant get it to work. Now I get all the different categories which is good but the posts that have the same category should be printent directly after and not with the same category name above.
2
Answers
You need to use the "get_cat_name( $category_id )" rather then "the_category()"
So in the function get_cat_name(), you need to pass the same category id which you are passing in the wp_query.
Here is your code and if you are wishing to show all the posts then you do not require to pass any category all you need to pass is the
post_per_page
If you wish to show the specific post of the respective category then you can use slug, term_id, etc and you need to inject the tax_query in your argument here is the sample code based on slug