How to move style from template file to section?

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

2 Answers
2

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.

Note-

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.

<?php   
    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' );
?>

Leave a Comment