Created
February 3, 2018 16:44
-
-
Save fumikito/eb5b558553038b4491fc474ca3b7a449 to your computer and use it in GitHub Desktop.
Template file shortcode
This file contains hidden or 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 | |
/** | |
* Register shortcode [my-template] | |
* | |
* File based short code. | |
* | |
* @param array $atts Shoutcode attribures. | |
* @param string $string Content wrapped in shortcode. | |
* @return string Rendered result. | |
*/ | |
add_shortcode( 'my-template', function( $atts = [], $string = '' ) { | |
// Get attributes default values. | |
$atts = shortcode_atts( [ | |
'template' => '', | |
], $atts, 'my-template' ); | |
// Buffer rendered result. | |
// For more details, see {http://php.net/manual/en/function.ob-start.php} | |
ob_start(); | |
// In this example, simply load template file. | |
get_template_part( 'template-parts/page', $atts['template'] ); | |
// Grab buffered strint output. | |
$content = ob_get_contents(); | |
// Clear output because this is shortcode! | |
ob_end_clean(); | |
// Remove all tabs and line breaks step by step. | |
// Explode rendered string with line break. | |
$lines = explode( "\n", $content ); | |
// Trim each line. | |
$lines = array_map( function( $line ){ | |
return trim( $line ); | |
}, $lines ); | |
// Filter empty line. | |
// Because, empty line causes unexpected 'p' in WordPress. | |
$lines = array_filter( $lines ); | |
// Now return them combineded with line break. | |
return implode( "\n", $lines ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment