4

I had a very basic wp_query, below:

// WP_Query arguments
$args = array (
    'post_type'              => array( 'post' ),
    'post_status'            => array( 'draft' ),
    'posts_per_page'         => '15',
);

// The Query
$posts = new WP_Query( $args );

This caused a 500 error. When I changed $posts back to the more traditional $query, everything was fine. Is $posts a reserved variable?

  • Where did you place this code? – engelen Mar 30 '16 at 8:03
  • 2
    it would be better if it had been prefixed in core, to avoid collision ;-) – birgire Mar 30 '16 at 8:54
  • 2
    @birgire Yes that makes no sense at all only prefixing $wp_query which is prefixed with wp_ and not othere like $post and $posts. I have seen a huge amount of users here which uses $posts as a local variable without knowing it is actually a reserved global, and almost always, their issue is related to this – Pieter Goosen Mar 30 '16 at 13:01
  • 2
    yes these global swamps can be muddy, we don't know what's gonna bite us in the feet when we go there, like demonstrated here ;-) But it's very natural to think one could use such generic variable names like $posts and $post @PieterGoosen – birgire Mar 30 '16 at 13:14
3

Is $posts a reserved variable

Yes, it is, $posts is the global variable which holds the array of posts from the main query. This is how it is set:

$GLOBALS['posts'] = & $wp_query->posts;

Just remember, $posts === $GLOBALS['posts']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.