How to detect when get_template_part() WordPress function fails

Nowadays, in most of modern WordPress themes, the function get_template_part() is one of their essential elements. It just takes review the structure of, for example the last official themes (…, Fourteen, Fifteen, Sixteen), to realize that WordPress themes have evolved, from a structure quite monolitic to a structure driven by content and formats. And one of the keys to this evolution is the get_template_part () function.

silent diversity

get_template_part() it’s actually an invaluable element of any modern WordPress theme that through its two parameters allows us to select dynamically what .php file (what part) is going to be loaded for displaying the current page (see the official documentation for further information) however, one of its characteristics is that, as the official documentation warns, get_template_part() fails silently, ie, when the function doesn’t find the part, it doesn’t say anything, doesn’t return any value…

But this is not completely exact because, the contrary is also true. When get_template_part() does find the part, in fact, it doesn’t return any value though, of course, the part it’s loaded so that, something appears on the screen. In any case, the thruth is that get_template_part() never returns a value. So, on this basis, how do we control when the function fails? ie, Without a returned value, how to differentiate between when a part has been actually loaded or when on the screen there is nothing?

Detecting when get_template_part() WordPress function fails

Our proposed solution is precisely based, not in the behaviour of the own function, but in the consequences of its activity because, while the function doesn’t return anything, its activity does produce something: a screen part. And we can effectively control whether the output appears or not.

The trick is that we can’t control a return value, but we can control the existence of the output.

The solucion is, in fact, very simple. Just, we need use the ouptut filter PHP functions when we are going to use get_template_part() and afterwards, instead of controlling the function, as I said, controlling the output.

get_template_part( $slug, $name );
$out = ob_get_contents();
if ( $out ) {
    // Nothing to do because get_template_part() has found the 'part' so, there is output thus, $out is not empty.
} else {
   // Here the code for error because, as get_template_part() has not found anything, $out is empty.

Have a nice WordPressing!

Leave a Comment

   Mandatory field
You can use these HTML tags inside the commment.
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>