Loading Templates with appthemes_load_template()

With advanced themes, sometimes it is important that your templates be given certain data to them when they load. If you’re creating an archive, wouldn’t it be nice to be able to simply create a loop like the following?

$posts = new WP_Query( "...query..." );
foreach( $posts as $post ) {
 
    $data = get_data();
    include( "content.php", $data );
 
}

The problem is that you can’t pass template files arguments like you can functions. Well, you couldn’t. We created a helper function appthemes_load_template() for just this special occasion.

Passing Data to Template Files

Reusing template files is easy with appthemes_load_template(). Here’s how it works:

$data = array(
   'variable_name' => $variable_data,
   'variable_name2' => $variable_data
);
appthemes_load_template( 'file you want to load', $data_to_pass );

Now, in your template file the variables you’ve set through the data argument are automatically made available.

<div class="some-class"><?php echo $variable_name; ?></div>
<div class="some-other-class"><?php echo $variable_name2; ?></div>

This allows you to make templates that are reusable, because they don’t rely on global data, such as template tags, in order to work. You simply load up the data array and they work.
 

Like this tutorial? Subscribe and get the latest tutorials delivered straight to your inbox or feed reader.

Your rating: none
Rating: 5 - 1 vote

Popular Add-ons

Classy

A Modern,Clean & Full-features Child theme for classipress

(5)
$49

Coups

A clean and advanced clipper child theme with extended features.

(8)
$39

CP-Tabber

Show specific custom fields as tabs on an ad detail page.

(3)
$12