I have this code that is displaying a list of my blogposts on my index.
What I would like is to add a category parameter to it, to only display a list of the posts with a specific category.
I don’t seem to be able to do it, without breaking everything…
Thanks for your precious help.
<?php $all_posts = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1 ) );
if ( $all_posts->have_posts() ):?>
<ul>
<?php while ( $all_posts->have_posts() ) : $all_posts->the_post(); global $post;
?>
<li class='sub-menu'>
<a href='#' class="exposition" data-id="<?php the_id();?>"><?php the_title(); ?></a>
<ul>
<li>
<?php the_content(); ?>
</li>
</ul>
</li>
<?php $images = get_field('gallery');?>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
As an alternative, consider using get_posts()?
It will require other changes to your code but you can easily create a query to include Categories, and then foreach through the results.
Update:
Here’s an equivalent to your code written with get_posts(). Take a copy of your own code first but the below would replace it all. Note the Category ID in the arguments – this is what you need to change to suit your needs.
get_posts() is a much simpler function for this kind of use case than WP_Query but is less flexible if you want complex queries.
<?php
$args = array(
'numberposts' => -1,
'category' => 1 //REPLACE THIS NUMBER WITH YOUR CATEGORY ID!
);
$all_posts = get_posts( $args );
if (count($all_posts) > 0) : ?>
<ul>
<?php
foreach ( $all_posts as $post ) : ?>
<li class="sub-menu">
<a href='#' class="exposition" data-id="<?php _e($post->ID);?>">
<?php _e($post->post_title);?>
</a>
<ul>
<li>
<?php _e($post->post_content);?>
</li>
</ul>
</li>
<?php
endforeach;
?>
</ul>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0