-
-
Save inc2734/fa4cb55f63ac89edeffeb65bcf827121 to your computer and use it in GitHub Desktop.
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 | |
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