Create Topic

WP Tavern Forums Create Topic

Create New Topic

Justin Tadlock

One simple example I use in my themes is to pass along the sidebar ID. So, let’s say I have a sidebar.php template to handle multiple dynamic sidebars. Instead of creating a template for each of the sidebars, I can pass the sidebar ID to the template so that it outputs the correct sidebar widgets.

So, when calling my footer sidebar, I can do something like and pass along the sidebar ID:

<?php get_sidebar( 'footer', [ 'sidebar_id' => 'footer' ] ) ?>

That will look for a sidebar-footer.php and fall back to sidebar.php. Let’s assume I don’t create a sidebar-footer.php. My main sidebar.php template could handle this footer sidebar (or any other) like so:

<!-- open html -->

<?php dynamic_sidebar( $args['sidebar_id'] ) ?>

<!-- close html -->

If all the sidebars have the same markup, there’s no need for individual templates. I can just pass the ID that I need.

This is an overly simple example, but I hope it illustrates how this feature can be used. As you get into more complex setups, you’ll find that you could use this in more and more ways.

Most templating systems for other PHP frameworks start with the notion that you’re passing data into templates. WordPress generally works based on a set of global variables and “template functions” (i.e., the_title(), the_content(), etc.). Other templating systems would usually pass that data along via a variable instead. Often, the idea is to separate the logic code from the template code. But, I’m starting to venture into a much larger discussion.






Newsletter

Subscribe Via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.