Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created February 3, 2018 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumikito/eb5b558553038b4491fc474ca3b7a449 to your computer and use it in GitHub Desktop.
Save fumikito/eb5b558553038b4491fc474ca3b7a449 to your computer and use it in GitHub Desktop.
Template file shortcode
<?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