Wordpress: get all posts of a custom type

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!

Answers


'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.


This get all posts of a custom type using get_posts:

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

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'

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


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

'posts_per_page' => 999999,

Need Your Help

Extern functions in C vs C++

c++ c

In *.h header files of a C library, should one declare functions

Windows.Forms.Timer OR System.Threading.Timer

c# .net timer

I have an application that runs many threads. Each thread should have a timer that checks for something in that thread's scope. My question is: Which timer I should use and what is the difference b...