TransWikia.com

Display a list of posts corresponding to a category

WordPress Development Asked on November 23, 2021

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; ?>

One Answer

As 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>

Answered by t2pe on November 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP