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
1

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}.

Leave a Reply

Your email address will not be published. Required fields are marked *