Returning Variables back into a template

If I put a function that I want to use in a template I can put it into functions.php

function myfunction(){
echo 'My String';
}

add_action('myfunction','myfunction');

Read More

and in a template file put:

do_action('myfunction');

This appears to only work if writing something out to the screen. If I wanted to return a variable instead to the page. E.g.

function myfunction(){
return 'My String';
}

$string = do_action('myfunction');

and capture it instead of print it. How would I do it?

Related posts

1 comment

  1. There’s filters for that.

    Example:

    add_filter( 'template_filter', 'wpse_102706_filter_callback', 10, 2 );
    function wpse_102706_filter_callback( $defaults, $case )
    {
        $args = wp_parse_args( array(
            'some_key' => 'some_modified_value'
        ), $defaults );
    
        return $args
    }
    

    Then in your template just add in the defaults:

    apply_filters( 'template_filter', array( 'some_key' => 'default_val' ), 'single' );
    

    More info in Codex about the Plugins API.

Comments are closed.