Imagine the following situation:

//header.php contains:
<header id="header">logo and navigation</header>

//my-template.php contains:
<?php get_header(); ?>
     <style type="text/css">#header { display: none; }</style>
     <div class="main-container-of-my-template"></div>
<?php get_footer(); ?>

This will disable <header> for my-template.php in the most modern browsers (except IE9) but it's not valid solution. Is there a way to use something like wp_enqueue_style(); directly in my-template.php to make it load that style in <head> in header.php? Just to make it valid.

I want to keep this modular, so I don't want to put if statement like this in header.php (it will not be stand-alone modular page template anymore):

<?php if(is_page_template( 'my-template.php' )){ ?>
<style type="text/css">#header { display: none; }</style>
<?php } ?>
  • not 100% sre what you mean but...what is it exactly your wanting to do? and why would you hide the navigation and logo. – somdow Jul 29 '12 at 11:47
  • I want to include <style> in header.php but I still want to have it in my-template.php and not move it entirely to header.php. It doesn't matter why I want to hide header. I just wanted to show idea where something can't be achieved using simple style.css. – Paul Jul 29 '12 at 11:55
  • basically you want to load a <style> in <head> section but doesn't want to keep the code in header.php, Right ? – amit Jul 29 '12 at 14:43

What about putting styles before the function get_header();

<style type="text/css">#header { display: none; }</style>
<?php get_header();?>
<div class="main-container-of-my-template"></div>
<?php get_footer(); ?>

However this is not recommended as it loads the styles even before the <html> not within the <head> section of your website, but as per your requirement this could be the only way to add styles by editing your my-template.php file.


Second way (recommended) to load scripts in <head> section without modifying header.php is to use themes functions.php to enqueue styles in <head>. Here's the code that does the trick -

Make sure you make a new new-style.css file in template directory with necessary stylings.

    function wpse_60052_load_style() { 
        if(is_page_template( 'my-template.php' )) { 
            wp_enqueue_style('mystyle', get_bloginfo('template_directory').'/new-style.css');
add_action( 'wp_enqueue_scripts', 'wpse_60052_load_style' );

Option one is to use the same is_page_template and use wp_enqueue_style which would add some stylesheet only if this page template is available.

Option two is to just embed this code to the page template header (this won't be visible in other templates obviously).

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.