Michael
Michael

Reputation: 2187

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!

Upvotes: 46

Views: 115738

Answers (5)

mustra
mustra

Reputation: 143

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

Upvotes: 2

Andrea
Andrea

Reputation: 16560

This get all posts of a custom type using get_posts:

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

Upvotes: 54

joseacat
joseacat

Reputation: 85

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

'posts_per_page' => 999999,

Upvotes: 0

jono
jono

Reputation: 1842

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

Upvotes: 57

Bobadevv
Bobadevv

Reputation: 366

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'

Upvotes: 8

Related Questions