Last active
December 8, 2018 19:07
-
-
Save webmandesign/8578ca85da784bdcff9730deab548b1f to your computer and use it in GitHub Desktop.
WordPress theme file locator and loader.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* File Class | |
* | |
* Helper class to locate and load files in child/parent | |
* theme only if they exist. | |
* | |
* Rename "Themeslug" according to your needs. | |
* Edit according to your needs... | |
*/ | |
class Themeslug_File { | |
/** | |
* Locate file by its relative path. | |
* | |
* Searches child theme first, before falling back to parent theme. | |
* If the file is not found, returns an empty string. | |
* | |
* @param string $path_relative | |
*/ | |
public static function get_path( $path_relative = '' ) { | |
$path_absolute = get_theme_file_path( $path_relative ); | |
if ( ! file_exists( $path_absolute ) ) { | |
$path_absolute = ''; | |
} | |
return $path_absolute; | |
} | |
/** | |
* Load a file using different PHP statements. | |
* | |
* @param string $path_relative | |
* @param string $statement | |
*/ | |
public static function load( $path_relative = '', $statement = 'require' ) { | |
$path = self::get_path( $path_relative ); | |
if ( ! empty( $path ) ) { | |
switch ( $statement ) { | |
case 'require': | |
require $path; | |
break; | |
case 'require_once': | |
require_once $path; | |
break; | |
case 'include': | |
include $path; | |
break; | |
case 'include_once': | |
include_once $path; | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WordPress theme file locator and loader
Rename
Themeslug
according to your needs (your WordPress theme slug).Edit & share according to your needs...
How to use
Copy the file into your theme and load it in
functions.php
file withrequire get_template_directory() . '/class-file.php';
(orrequire get_template_directory() . '/path/to/class-file.php';
).To find the child/parent theme file path use
Themeslug_File::get_path( 'relative/path/to/file.php' );
. If the file does not exist, empty string is returned.To load a child/parent theme file use
Themeslug_File::load( 'relative/path/to/file.php', 'require' );
. If the file does not exist, nothing is loaded. Therequire
argument is the default value, so it can be committed, or replaced withrequire_once
orinclude
orinclude_once
depending on your needs.