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

How do I add $tzDesc and $tzEmbed (and other variables) to the $post object in the following function so that I can display the values in my theme files by inserting <?php echo $tzDesc; ?>?

add_action( 'the_post', 'paginate_slide' );

function paginate_slide( $post ) {

    global $pages, $multipage, $numpages;

    if( is_single() && get_post_type() == 'post' ) {

    $multipage = 1;
    $id = get_the_ID();
    $custom = array();
    $pages = array();
    $i = 1;

    foreach( get_post_custom_keys() as $key )
        if ( false !== strpos( $key, 'slide' ) )
            $custom[$key] = get_post_meta( $id, $key, true);

    while( isset( $custom["slide{$i}-title"] ) ) {

        $page = '';
        $tzTitle = $custom["slide{$i}-title"];
        $tzImage = $custom["slide{$i}-image"];
        $tzDesc = $custom["slide{$i}-desc"];
        $tzEmbed = $custom["slide{$i}-embed"];

        $page = "<h2>{$tzTitle}</h2><img src='{$tzImage}' />";
        $pages[] = $page;
        $i++;
    }

    $numpages = count( $pages );
    }
}

If you know and can provide an answer can you please be very detailed in how the code should be structured because my knowledge of php is very minimal and I have tried to do this numerous already without any success. Thanks.

Related posts

Leave a Reply

1 comment

  1. 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;