Skip to content

Instantly share code, notes, and snippets.

@csrui
Last active September 19, 2019 22:59
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 csrui/d9a6e7890a0c551ccf80e7d58a529656 to your computer and use it in GitHub Desktop.
Save csrui/d9a6e7890a0c551ccf80e7d58a529656 to your computer and use it in GitHub Desktop.
Load partials not needing globals. Just pass arguments to the functions.
<?php
/**
* @wordpress-plugin
* Plugin Name: FCG Partials.
* Description: Do not depend on globals to pass variables to template parts.
* Version: 1.0.0
* Author: Gulbenkian
* Author URI: https://github.com/gulbenkian/
* License: GPL-2.0+
*/
if ( ! function_exists( 'fcg_parcial' ) ) {
/**
* Use template partials with parameters.
*
* No need for globals, pass the parameters to the function.
*
* @todo Add caching based on partial and arguments.
*
* @since 1.0.0
*
* @param string $partial_template
* @param array $arguments
* @return void
*/
function fcg_partial( string $partial_template, array $arguments = [] ) {
/**
* Change location of the partial.
*
* A custom location (folder) can be defined using the filter.
*
* @since 1.0.0
*
* @param string $prefix Defined prefix.
* @param array $arguments The passed arguments.
* @param string $partial_template Partial name.
* @return string New prefix.
*/
$prefix = apply_filters( 'fcg_partial_prefix', '', $arguments, $partial_template );
$__partial = locate_template( [ $prefix . $partial_template . '.php' ], false );
if ( empty( $__partial ) ) {
return false;
}
if ( ! is_readable( $__partial ) ) {
return false;
}
/**
* Change partial arguments.
*
* @since 1.0.0
*
* @param array $arguments The passed arguments.
* @param string $partial_template Partial name.
* @return array Updated arguments list.
*/
$arguments = apply_filters( 'fcg_partial_arguments', $arguments, $partial_template );
if ( ! empty( $arguments ) ) {
// phpcs:disable WordPress.PHP.DontExtract.extract_extract
extract( $arguments );
// phpcs:enable WordPress.PHP.DontExtract.extract_extract
}
include $__partial;
}
}
if ( ! function_exists( 'get_fcg_parcial' ) ) {
/**
* Return the content of the template partial.
*
* @since 1.0.0
*
* @param string $partial_template
* @param array $arguments
* @return string
*/
function get_fcg_partial( string $partial_template, array $arguments = [] ) {
ob_start();
fcg_partial( $partial_template, $arguments );
$content = ob_get_clean();
/**
* Change the output from the partial.
*
* @since 1.0.0
*
* @param string $content The rendered partial.
* @param array $arguments List of arguments passed to the partial.
* @param string $partial_template Partial name.
* @return string Updated rendered partial.
*/
return apply_filters( 'fcg_partial_content_after', $content, $arguments, $partial_template );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment