I’m working on a WordPress site that automatically displays an h2
on the page as what the page/post is titled. I want to manually create h1
for some pages and have the h2
to be hidden if the h1
appears.
Is there a way to do that?
I’m working on a WordPress site that automatically displays an h2
on the page as what the page/post is titled. I want to manually create h1
for some pages and have the h2
to be hidden if the h1
appears.
Is there a way to do that?
You must be logged in to post a comment.
There are two ways to do this, though one is arguably better than the other.
Use JavaScript (Works, but not optimal)
The first way to do this is by using JavaScript. I’m not a fan of using this approach because it requires a web browser to perform the toggling. This negatively impacts SEO because, to search engines, the element still exists in the document.
Still, if you opt for this approach, here’s how you can do it…
Assuming that you page is setup something like this:
Then your JavaScript – jQuery-based (since WordPress uses jQuery) – would look like this:
You can make this code is a little bit clearer by providing ID’s or class names on your heading elements. For example, say you’ve got the heading elements named as such:
Then your JavaScript could look like this:
Do it on the server-side
The better way to do this would be to actually set it up in the template file on the server-side.
Say, for example, you want to show an
h1
only on single posts or pages but anh2
on archive pages or listing pages. You’d do it like this:This is better because the processing occurs on the server-side so that the document served to the requesting agent (that is, the search engine or the web browser) will only see a single-element.
I do this in my header.php file: