Reputation: 15
In my news page (home.php) I have the search by category widget (dropdown) that will lead me to a page with the result of my research for a specific category (archive.php). Let's say for example, that I chose "Events" in the dropdown list, I'll be redirected to a page where only the posts within the "Events" category are displayed.
A few years ago, I took a plugin for displaying my posts in the same page, but now I'm putting back pagination but I have a problem: I can't find how to display only the posts of the category resulting of my search. For now, it displays all the posts.
I've done some research about it, tried a lot of solutions, tried to put back the classic code of an archive page (without any success) and went to this Wordpress page about get_the_category but I can't seem to find anything conclusive: https://developer.wordpress.org/reference/functions/get_the_category/
Now my code is completely a mess and tbh I have no clue of what I'm doing anymore... Plus I want to display only 8 posts per page, giving me more complications.
Here is what I have now
<div>
<?php
$cats = get_categories();
foreach ($cats as $cat) {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 8
);
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query($args);
while ($wp_query -> have_posts()) : $wp_query -> the_post($cat->cat_ID); ?>
<div> Here is my post </div>
<?php endwhile; } ?>
</div>
<?php the_posts_pagination( array(
'mid_size' => 2
) ); ?>
<?php $wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
Upvotes: 1
Views: 1118
Reputation: 26
Assuming that you are already on the category page, you should simply retrieve the category name and pass it to your WP_Query args, which will filter all the posts to be displayed by category!
<?php
// Retrieve current category name
$categoryName = get_the_category()[0]->name;
// Set args for query and pass category name
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 8,
'category_name'=> $categoryName
];
// Initiate WP Query
$wpQuery = new WP_Query($args);
// Loop through all posts in the query
while ($wpQuery->have_posts()) {
$wpQuery->the_post(); ?>
<div>Your post</div>
<?php } ?>
Upvotes: 1