Created
December 21, 2015 03:59
-
-
Save fumikito/e82762de8da104ef096e to your computer and use it in GitHub Desktop.
Alternative of WordPress' get_template_part which can accept arguments.
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 | |
/** | |
* A template loader which accepts arguments. | |
* | |
* @param string $slug | |
* @param string|array $name | |
* @param array $args Arguments to pass. | |
* @param bool $echo If false, return string. | |
* @param string $glue Default is '-'. You can specify '/' which means directory separator. | |
* | |
* @return null|string | |
*/ | |
function hammeplate( $slug, $name = '', $args = [], $echo = true, $glue = '-' ) { | |
$file = []; | |
if ( ! $name ) { | |
$file[] = $slug; | |
} elseif ( is_array( $name ) ) { | |
for ( $i = count( $name ); $i > 0; $i -- ) { | |
$file[] = $slug . $glue . implode( $glue, array_slice( $name, 0, $i ) ); | |
} | |
$file[] = $slug; | |
} else { | |
$file[] = $slug . $glue . $name; | |
$file[] = $slug; | |
} | |
$dirs = [ get_stylesheet_directory() ]; | |
if ( is_child_theme() ) { | |
$dirs[] = get_template_directory(); | |
} | |
$path = ''; | |
foreach ( $file as $f ) { | |
foreach ( $dirs as $dir ) { | |
$p = $dir . DIRECTORY_SEPARATOR . $f . '.php'; | |
if ( file_exists( $p ) ) { | |
$path = $p; | |
break 2; | |
} | |
} | |
} | |
if ( ! $path ) { | |
return $echo ? null : ''; | |
} | |
// Enable vars. | |
global $posts, $post, $wp_query, $wp_rewrite, $wpdb; | |
if ( $args ) { | |
extract( $args ); | |
} | |
if ( $echo ) { | |
include $path; | |
} else { | |
ob_start(); | |
include $path; | |
$output = ob_get_contents(); | |
ob_end_clean(); | |
return $output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment