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; ?>
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; ?>
Share
Improve this question
edited Jul 22, 2020 at 19:00
pual
asked Jul 22, 2020 at 13:11
pualpual
1136 bronze badges
2
|
1 Answer
Reset to default 0As an alternative, consider using get_posts()?
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>
$query = new WP_Query( array( 'category_name' => 'test' )
then there is the if but I don't know how to checkif = 'test'
– pual Commented Jul 22, 2020 at 13:28