Skip to content

Instantly share code, notes, and snippets.

@inc2734
Created August 3, 2016 04:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inc2734/fa4cb55f63ac89edeffeb65bcf827121 to your computer and use it in GitHub Desktop.
Save inc2734/fa4cb55f63ac89edeffeb65bcf827121 to your computer and use it in GitHub Desktop.
<?php
class TemplatePart {
protected $template;
protected $slug;
protected $vars = array();
protected $WP_Query;
public function __construct( $template, $slug = '' ) {
global $wp_query;
$this->template = $template;
$this->slug = $slug;
$this->WP_Query = $wp_query;
}
public function set_var( $key, $value ) {
if ( null === $this->WP_Query->get( $key, null ) || ! isset( $this->vars[$key] ) ) {
$this->vars[$key] = $value;
$this->WP_Query->set( $key, $value );
}
}
public function set_vars( $vars ) {
foreach ( $vars as $key => $value ) {
$this->set_var( $key, $value );
}
}
public function render() {
get_template_part( $this->template, $this->slug );
foreach ( $this->vars as $key => $value ) {
$this->WP_Query->set( $key, null );
}
}
}
$vars = [
'_foo' => 'foo',
'_bar' => 'bar',
];
$TemplatePart = new TemplatePart( 'template-parts/foo' );
$TemplatePart->set_vars( $vars );
$TemplatePart->render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment