Only Show a Theme’s Title Tag in WordPress if No Heading 1 is Present in the Content

With the Gutenberg editor, you can insert h1 tags in your actual content. You may want to do this if, for example, you’re creating a hero image and want the Heading 1 tag on top of that image.

In this case, you probably don’t want to have a heading 1, then another heading 1 below, or even to replace that hero image’s heading with a heading 2. It’s all just sloppy and could hurt your SEO rankings.

If you have access to your theme’s template files, we can easily check to see if the content (ie, the_content in WordPress) contains an H1 tag, and only show the theme’s heading 1 if that’s not true.

<?php $has_h1 = get_the_content();
if (!str_contains($has_h1, '<h1')) { ?>
<h1 class="entry-title"></h1>
<?php } ?>

So that basically says:

  1. Grab all of the content for this page and store it in the $has_h1 variable.
  2. If the string <h1 isn’t in the content, show the theme’s Heading 1 setup.

It’s as easy as that, a conditional statement for Heading 1 tags in WordPress!

Up Next: Flaw with Gravity Forms GF_IMPORT_FILE