Access our premium support and let us know your problems, we will help you solve them.

0
No products in the cart.
  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #9965
    blankmichael
    Participant

    I have this strange issue. I want to fetch all posts that are of a custom type, here’s my snippet.

    $query = new WP_Query(array(
        'post_type' => 'custom',
        'post_status' => 'publish'
    ));
    
    
    while ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        echo $post_id;
        echo "<br>";
    }
    
    wp_reset_query();
    

    This only gets me 6 of them, while I have more than 50 records matching that criteria in the database. Can anyone tell me where I have gone wrong?

    Many thanks!

    #9968
    blankbobadevv
    Participant

    The number of posts to return are set under settings > reading

    You can pass the number of posts for your query to return using.

    'posts_per_page' => 'number of posts'
    
    #9970
    blankjono
    Participant

    'posts_per_page' => -1,

    Add this to the WP_QUERY array of arguments and it should return all of the posts of this custom post type.

    #9966
    blankjoseacat
    Participant

    It is advisable to use an integer instead of ‘-1’ For example:

    'posts_per_page' => 999999,
    
    #9969
    blankandrea
    Participant

    This get all posts of a custom type using get_posts:

    $posts = get_posts([
      'post_type' => 'custom',
      'post_status' => 'publish',
      'numberposts' => -1
      // 'order'    => 'ASC'
    ]);
    
    #9967
    blankmustra
    Participant

    You should never use:

    'posts_per_page' => -1
    

    It slow and not effective, if you are talking about SQL Query speeds. So it is much better to use some large integer.

    This is a performance hazard. What if we have 100,000 posts? This could crash the site. If you are writing a widget, for example, and just want to grab all of a custom post type, determine a reasonable upper limit for your situation.

    More details here:
    https://10up.github.io/Engineering-Best-Practices/php/#performance

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.