Filter the blog’s title without using global variables

You can encapsulate the logic in a class:

class NameSwitch
{
    private $state = false;

    private $string;

    public function __construct( $string )
    {
        $this->string = $string;
    }

    public function change_state()
    {
        $this->state = ! $this->state;

        return $this->state;
    }

    public function replace( $output, $show = NULL )
    {
        if ( 'name' !== $show )
            return $output;

        if ( ! $this->state )
            return $output;

        return $this->string;
    }
}

Then create an instance of this class on template_redirect to restrict it to the front-end and assign the methods as callbacks as you did before:

add_action( 'template_redirect', function()
{
    $switch = new NameSwitch(
        "<span class="info-style">Info</span><span class="psi-style">Psi</span><span class="md-style">.md</span>"
    );

    add_action( 'wp_head',   [ $switch, 'change_state' ], PHP_INT_MAX );
    add_action( 'wp_footer', [ $switch, 'change_state' ], 0 );
    add_filter( 'bloginfo',  [ $switch, 'replace' ], 10, 2 );
});

But what you should really do is:

Replace the call to bloginfo() in your child theme with a custom function or do_action('custom_name'). Then you wouldn’t have to run the filter at all, just return your custom value.

Leave a Comment