1

I've got two foreach loops, and I'm using an object generated by WordPress.

In my mind, these should both work the same. However, they don't. Notice $post and $not_a_post in the loop:

A:

$array_A = array( 'posts_per_page' => 2 );
$get_posts_A = get_posts( $array_A );

foreach ( $get_posts_A as $post ) { //uses $post
    the_title(); 
}

B:

$array_B = array( 'posts_per_page' => 5 );
$get_posts_B = get_posts( $array_B );

foreach ( $get_posts_B as $not_a_post ) {  //uses $not_a_post
    the_title(); 
 }

The only difference is that I use a variable $post for conditional first loop.

I always thought (apparently, incorrectly) the second conditional variable was just a placeholder. So I could do $x, $y, etc.

Can someone explain to me why this foreach loop requires the variable $post ?

2
  • Can you explain what the expected result is and what you're getting instead...? This also seems to have little to do with PHP, but instead with Wordpress' idiosyncrasies. Commented Feb 27, 2014 at 15:33
  • 2
    Please do as @deceze says and post more info, but in the mean-time. In pure PHP terms, the difference between the two (in terms of what you are asking) is that the first foreach loop has the variable $post available inside it, the second has $not_a_post. Who knows what get_posts does or the_title() requires, as you don't show us that code. Commented Feb 27, 2014 at 15:37

1 Answer 1

6

That's because the_title() relies on a variable named exactly $post coming from the outer scope, which is a terrible design idea by the way - it should be passed as a parameter to the function, e.g.:

the_title($some_id || $some_resource);

EDIT: actually WP allows you to pass the post id, check the code here.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, so this wouldn't be the case outside of WordPress. Could you elaborate on the parameter to the function?
Thanks for mentioning wordpress' global variable mess... Could not have said it better
That's clearer. Is there anything I could change to the current loop in regard to that, or is it a quirk I can't avoid?
@tmyie you can call get_the_title($not_a_post). Or you can use a cleverly coded software : ))
@Thomas That statement can be abbreviated to Don't use Wordpress. ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.