I built a custom theme on WordPress with a static front page and no page set in Settings > Reading Settings > Front page displays as a posts page. I'd like to display posts, however, based on their categories throughout the site on different static pages. Therefore, I will never declare a posts index page through the console. And so I use the $wp_query function.
How can I add a filter to this script that only displays posts in the category "apples" (for example)? Right now, this script shows all posts regardless of category.
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php the_date(); ?>
<?php endwhile; ?>
<?php if ($paged > 1) { ?>
<p><?php previous_posts_link('Previous page'); ?>
<?php next_posts_link('Next page'); ?></p>
<?php } else { ?>
<p><?php next_posts_link('Next page'); ?></p>
<?php } ?>
<?php wp_reset_postdata(); ?>
You have to use
category_name
(string - use category slug) orcat
(int - use category id), to get post by category inWP_Query::query()
.
Here is an example:
$category_name = 'apples'; //replace it with your category slug
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged=' . $paged . '&category_name=' . $category_name);
//...
//...
Hope this helps!