Trick: dynamic closing of tags in the theme

It seemed to me that the trick described here is convenient and not everyone uses it. In addition, the technique from this article can be used in other cases, and I think it's worth keeping it in your knowledge bank to use at any time when needed.

I won't say that I've made a lot of themes and sometimes it annoyed me, but I will say that I haven't made so many themes, but every time, it annoyed me. I was annoyed until one day it struck me and this trick came to mind. For some reason, I didn't think to write about it until recently - why didn't I think about writing about it earlier?

And now in order...

Everyone who has created a theme for WordPress has probably encountered a situation where there is a page structure like this:

<?php get_header(); ?>

<div id="content">

	<!-- loop output or some other content output -->

</div><!--#content-->

<?php
get_sidebar();
get_footer();

And this structure is used for all types of pages: home.php, page.php, single.php, archive.php, category.php, search.php, 404.php, page-name.php, etc. That is, no matter what page we create, it will have a similar structure.

Hence the question arises, why not hide the <div id="content"> tags in the header and </div><!--#content--> in the sidebar. After all, the structure is the same everywhere, why repeat it in all template files. Let them be in one file. And then the structure will look simpler:

<?php
get_header();

	// loop output or some other content output

get_sidebar();
get_footer();

But if we do that, then we can't remove the sidebar anywhere: get_sidebar();. Because an important closing tag is inside it. And it needs to be removed, or if not needed now, it may be needed in the future...

Before reading further, think for yourself how you can put these tags in the common files header.php, sidebar.php, or footer.php so that the presence or absence of the sidebar does not break anything?

Solution

The solution is very simple and it consists of using the little-known and rarely used function did_action().

It is necessary to place <div id="content"> in the file header.php and place </div><!--#content--> in the file sidebar.php. Then duplicate the display of </div><!--#content--> in the footer.php file, but with a condition - to display this tag only if the get_sidebar() function has not been called, in which the get_sidebar hook is triggered...

That is, the code at the beginning of footer.php will look like this:

// if the sidebar was not called, the necessary tags are not closed - let's close them...
if( ! did_action('get_sidebar') )
	echo '</div><!--#content-->';

did_action() works lightning fast, so if someone has a question about performance at what seems to be an unnecessary place, it's unnecessary...

That's all, subscribe, like, and something else there...