Using conditional functions in WordPress

When creating custom themes for WordPress, often you’ll need to load different styles or scripts for a specific page template, or for the home page. One way to do it is to create a different header or footer that includes those files, and then load the custom header or footer from the page template:

// load a custom header or footer
get_header('custom');
get_footer('custom');

A better way to do it is to use conditional functions in your theme’s functions.php file. You can test for a specific page template, or for the front page. This will help you keep your template files clean and reduce code duplication. (Keep things DRY: don’t repeat yourself.)

Here’s a handy way to load different styles depending on the page template:

// your custom page styles
if (is_page_template('page-custom.php')) {
  wp_enqueue_style( 'custom-styles', get_template_directory_uri() . '/css/custom.css', array(), '1.0.0' );
};

Load a JavaScript file in the footer only on the home page:

// front page JS
if (is_front_page()) {
   wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/js/custom-script.js', array(), '1.0.0', TRUE );
}

You can also use these functions within your template files such as header.php and footer.php, but you might as well put it in the functions.php file since you will be loading other scripts there. By keeping it all in one place, you can change things more easily down the road.

From the WordPress Code Reference:

is_page_template()

is_front_page()

Leave a Reply

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