Conditionally loading template files

In this technique, we use existing WordPress filters to dynamically change the template based on custom conditions. WordPress executes a filter called template_include, just before loading the default template, based on the hierarchy we discussed earlier. In the template hierarchy section, we changed the template by using the preceding templates in a given path. The use of this filter allows us to change any template in any given path. Let's take a look the following code to understand the implementation of this technique:

add_filter( 'template_include', 'wpquickstart_conditional_template', 99 ); function wpquickstart_conditional_template( $template ) { if ( is_page( 'portfolio' ) ) { $new_template = locate_template( ...

Get WordPress Development Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.