7

Is there a way to automatically run get_header() at the beginning of template and get_footer() at the end of it?

Currently my code is too repetitive with those calls.

I've been looking for a way to do this, but I can't find it in Google.

  • 2
    Calling get_header() and get_footer() directly is the appropriate way to do it in your templates. – Pieter Goosen Apr 27 '14 at 10:38
  • 1
    @PieterGoosen I see, if that's the recommended way I guess I should live with it. It's just that having get_header() on every single template file doesn't seem clean. – hrsetyono Apr 27 '14 at 10:41
11

Looking at wp-includes/template-loader.php … there seems to be a way:

if ( $template = apply_filters( 'template_include', $template ) )
    include( $template );

You could hook into that filter, handle the including in a callback function and return FALSE.

Sample code, not tested:

add_filter( 'template_include', function( $template ) {

    get_header();
    include $template;
    get_footer();

    return FALSE;
});
  • You're the man! This should be standard! THANKS A LOT – hrsetyono Apr 27 '14 at 10:53
  • @DarcCode : I agree that these function calls should be more automatic but, while this may work for you, it does limit the flexibility of the individual template files-- that is, it becomes impossible to add code before get_header() in a template file, which is sometimes quite convenient. – s_ha_dum Apr 27 '14 at 14:59
  • True that, I'm still learning wordpress, so I haven't made complex site yet. But in what case you need to put code before get_header? – hrsetyono Apr 27 '14 at 15:12
  • 1
    I hadn't seen many use cases for stuff before header, however these functions accept header/footer name argument for loading different headers, which can be very much required in more complex sites. – Rarst Apr 27 '14 at 16:58
  • @Rarst that's a good point to mention... The current example is limited in flexibility, you could extend it further adding your own filter to optionally pass in header($params)/footer($params). – Adam May 1 '14 at 5:11
3

@scribu proposes a method for reducing code repetition in WordPress templates which he calls theme wrappers, which achieves what you're looking for. The roots theme uses a slightly modified version of this method.

  • 3
    Summary of the method would be nice to include in answer. Links die. – Rarst Apr 29 '14 at 21:45

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.