2

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');

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?

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.