How to remove a file included in parent theme with locate_template() via child theme?

In my theme I use locate_template() to load the various parts of my functions library. I’m looking for a way to not include one of those files when using a child theme. I tried adding locate_template('same_file_name.php', false); to my child theme’s functions.php but it is still included.

CLARIFICATION EDIT: I don’t want to prevent this file from being used by child themes. In general I want this file to be included when I am using a child theme. I am looking for something to add to a child theme when I don’t want to use it.

Related posts

3 comments

  1. An alternative solution that takes inspiration from both answers by @Milo and @toscho.

    create your own function to load template, e.g.

    if ( ! function_exists('my_locate_template') ) {
      function my_locate_template( $template = '', $load = false, $once = true ) {
        $filtered = apply_filters('allow_child_load_' . $template, true);
        if ( ! is_child_theme() || $filtered ) return locate_template($template, $load, $once);
        return false;
      }
    }
    

    Then in your parent theme load files using my_locate_template('same_file_name.php').

    In this way your files will be always loaded in parent theme and when using child theme, you can use the filter to exclude some files.

    add_filter('allow_child_load_disallow-this.php', '__return_false'); 
    

    and after that the file disallow-this.php, will not be loaded in that child theme.

    Also note the function is wrapped in if (! function_exists('my_locate_template') ) { so, if you want, you can completely replace it in a child theme.

    Simple, flexible, and with comfortable defaults.

  2. You could offer a filter for these files in your parent theme. Then you can decide in each child theme separately which files should be loaded:

    $files_to_include = array(
        'foo.php',
        'bar.php'
    );
    $files_to_include = apply_filters(
        get_template() . '_files_to_include',
        $files_to_include
    );
    
    if ( ! empty ( $files_to_include ) )
    {
        foreach ( $files_to_include as $file )
            locate_template( $file );
    }
    

    In a child theme you can remove some files from that array now:

    add_filter( get_template() . '_files_to_include', function( $files )
    {
        $bar_key = array_search( 'bar.php', $files );
    
        if ( FALSE !== $bar_key )
            unset( $files[ $bar_key ] );
    
        return $files;
    });
    
  3. You could wrap the locate_template call in a check for is_child_theme in your parent theme so it will be ignored:

    if( ! is_child_theme() ){
        locate_template( ... );
    }
    

Comments are closed.