9

For example, on my blog pages i use get_header('blog');, but i don't want to create a new header template called header-blog.php, because i just want to make a small adjustments. Is it possible to somehow get this name parameter in my header.php file?

1 Answer 1

8

There is an action get_header that you can use. In your theme’s functions.php, register a callback for that action:

add_action( 'get_header', function( $name ) {
    add_filter( 'current_header', function() use ( $name ) {
        // always return the same type, unlike WP
        return (string) $name;
    });
});

You could also write a little helper class that you can reuse:

class Template_Data {

    private $name;

    public function __construct( $name ) {

        $this->name = (string) $name;
    }

    public function name() {

        return $this->name;
    }
}

add_action( 'get_header', function( $name ) {
    add_filter( 'current_header', [ new Template_Data( $name ), 'name' ] );
});

In your header.php, you get the current part/name with:

$current_part = apply_filters( 'current_header', '' );

You can do the same with get_footer, get_sidebar and get_template_part_{$slug}.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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