简体   繁体   中英

Looping through Wordpress posts using a query + have_posts() only returns a fraction of them

I am trying to create a custom HTML sitemap. I am using the following PHP code to retrieve all the posts in a website:

         $args = array(
        'post_type' => 'post'
    );

    $post_query = new WP_Query($args);

    if($post_query->have_posts() ) {
        while($post_query->have_posts() ) {
            $post_query->the_post();
            ?>
            <a href=" <?php the_permalink(); ?>"><?php the_title(); ?></a>
            <?php
            }
        }

    wp_reset_postdata();

For some reason, the above code is only printing the links of the 10 most recent posts. I have more than 30 posts on my website. As I am not very comfortable with PHP, is there something wrong with the above code? Is there a different way I can try to achieve the same output? Thank you.

In order to show more posts on one page, also the regular Wordpress settings can be adapted, in the backend under Settings > Reading > Blog pages show max. XX pages Settings > Reading > Blog pages show max. XX pages (exact terms could be a bit different, I am usually using another language)

Alternatively you can add an according parameter in the query arguments (the $args array), for example 'posts_per_page' => 30, .

You need to set the posts_per_page argument in your query. -1 is equal to all posts.

     $args = array(
    'post_type' => 'post',
    'posts_per_page' => -1
);

$post_query = new WP_Query($args);

While both of the answers are correct. Let's look at some reasons why you may want to do one over the other.

Changing Setting > Reading > Blog pages show at most.

This has the potential to affect other queries on the site that do not have a posts_per_page setting in them . This has the ability to have hidden and unintended consequences when interacting with other plugins.

Using

     $args = array(
    'post_type' => 'post',
    'posts_per_page' => -1
);

$post_query = new WP_Query($args);

Has the possibility to create an endless scrolling page depending on how it is being used. 300 posts? no problem they just got dumped onto the page.

You may want to consider limiting them based on the possible design to something that is user friendly and using pagination to handle extra.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM