Loading a template file from a sub folder

This can be useful for organisation but also for building functionality in a component or modular way or in a plugin.

<?php
add_filter( 'template_include', 'pattern_archive_template' );
function pattern_archive_template( $template ){
    if( is_post_type_archive( 'pattern' ) ){
       if( $_template = locate_template( 'template-parts/archive/archive-pattern.php' ) ){
            $template = $_template;
       }
    }   
    if( is_post_type_archive( 'pattern' ) ){
       if( $_template = locate_template( 'template-parts/archive/archive-pattern.php' ) ){
            $template = $_template;
       }
    }   
   return $template;
}

For example this means we can store the template files with the register custom post type script. In that example we would use:

<?php
$_template = locate_template( 'component/custom-post-type/pattern/archive-pattern.php' ) ){
// Or
$_template = locate_template( 'component/custom-post-type/pattern/single-pattern.php' ) ){

Search the site

Share this page:

Newsletter

Subscribe to get regular news and updates

  • This field is for validation purposes and should be left unchanged.