Is it reasonable to modify the $post variable in WordPress during the loop?

So I’m starting to write a WordPress theme, and I’m trying to pass some variables from The Loop in my index.php to my actual content renderer in content.php.

Due to scope issues, I can’t just create a variable in index.php then try and access it in content.php. The idea of using global makes me shudder, so I thought perhaps I’d tag it onto the $post variable (which is already global). Is this a standard practice? Is there any reason I wouldn’t want to besides accidentally modifying a standard $post member var? Is there a idiomatic WordPress way to do this?

Read More

Here is an example of my index.php:

$post->is_n = false; # bad idea?                                
if($post_number === $n){
    $post->is_n = true
}
get_template_part( 'content', get_post_format() );

Then in my content.php:

if($post->is_n){$article_classes .= " is-n";}

Related posts

Leave a Reply

2 comments

  1. The $post variable already is a global within WordPress so creating or not creating another global to pass the value would really just be a matter of style more than anything else. WordPress makes pretty extensive use of global values on its own, given its genesis in pre-OOP PHP 4.x days.

    Attaching the value to $post would work, however there’s a chance the $post object won’t be completely destroyed between loop iterations, so your custom property may end up on a later iteration of the $post variable and potentially cause unintended side effects if you are not careful. As well, you’d have to be sure to namespace the property appropriately as to not conflict with future WordPress changes to $post.

    Creating a new global to pass the variable wouldn’t be out of the ordinary within WordPress, attaching custom properties to the $post variable would be a little unusual. If you wanted to namespace things and keep your values out of $_GLOBAL, you could create a quick registry class, but that may be overkill in this case.

  2. Modifying the $post variable is common, though I would probably choose a different design then the one you describe. But as one is learning one must find these things out for him self :^)

    When you have modified the $post variable you can call upon wp_reset_postdata function. This is more commonly used when you play with the WP_Query object.