How do I make my function add variables/values to the $post object?

Like any other php object, you can add items to the $post object like so:

$post->my_new_val_name="my new value";

I don’t know exactly what you’re trying to do, but inside a function hooked to the_post, you can assign new values and return the object.

function my_func($post) {

    $post->my_new_val_name="my new value";
    return $post;

}
add_action( 'the_post', 'my_func' );

However, in your template file, you won’t be able to just echo $my_new_val_name as you’re suggesting… the the_post() function doesn’t extract values that way. You’ll have to reference the post object explicitly. Like:

echo $post->my_new_val_name;

Leave a Comment