Answer a question

When creating a custom wordpress query, why would someone set their 'numberposts' to -1? What is the outcome? I've googled a bunch and can't seem to find this (probably) very simple answer!

ex: $args = array( 'numberposts' => -1);

Answers

Edited 3/31/2020 to correct inaccuracies (see original answer below)

To set the number of posts to be retrieved by the get_posts() function.

If the $args array in the original question were to be passed to the get_posts() function, it would retrieve all of the published posts in the database. So if you called this function in the template file of a site with 736 published posts, it would report Posts in Get Posts: 736

function get_all_posts(){
    $posts = get_posts(array('numberposts' => -1));
    echo '<h1>Posts in Get Posts: ' . count($posts) . '</h1>';
}

numberposts does not have an effect when used as an argument to WP_Query.

Note: in contrast to what commenter Toskan wrote below, it is not necessary to pass 'posts_per_page'=> -1 in order to achieve the result above. In my tests the function above and the function that follows did the same thing regardless of the total number of posts in the DB.

 function get_all_posts(){
    $posts = get_posts(array('numberposts' => -1, 'posts_per_page' => -1 ));
    echo '<h1>Posts in Get Posts: ' . count($posts) . '</h1>';
}

However, they are correct that if you set 'posts_per_page' to a positive value, it will override whatever value you pass in the 'numberposts' argument. It is also possible that if 'posts_per_page' is set in a filter and you set 'suppress_filters' to false, it might override the value of 'numberposts' regardless.

Previous (incomplete and inaccurate, but accepted) answer:

Simple Answer:

To return all of the results of the query.

Longer Answer:

The purpose is to set the WordPress pagination system to display all the posts that are available in the query. If you change numberposts to a positive integer it will display only number of posts per page.

For example, if your query would ordinarily return 150 results, setting numberposts to 15 would give you the first 15 results. Setting it to 150 would give you all the results. However, if the number of results increased it would continue giving 150 results. So -1 is used to essentially hard code getting all the results.

In PHP -1 is a common way of expressing "give me everything."

Note: 'numberposts' and 'posts_per_page' can be used interchangeably.

https://codex.wordpress.org/Template_Tags/get_posts

I prefer to use posts_per_page because it expresses the intent more clearly.

Logo

更多推荐