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?

  • nevermind; solved it. For anyone interested: <?php if(h1==null) { ?> <h2 id="post-<?php the_ID(); ?>"><?php the_title(); ?></h2> <?php } else { ?> <h2 style="display: none;" id="post-<?php the_ID(); ?>"><?php the_title(); ?></h2> <?php } ?> – Lucy Dec 22 '11 at 18:29
  • Lucy, welcome! You should post your comment as an answer, and then you can accept it, and that will show the question as solved. – Lea Cohen Dec 25 '11 at 9:58

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:

<h1><?php the_title(); ?></h1>
<h2>Some other text.</h2>

Then your JavaScript - jQuery-based (since WordPress uses jQuery) - would look like this:

if($('h1').is(':visible')) {
} // end if

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:

<h1 id="title"><?php the_title(); ?></h1>
<h2 id="alt-title">This is a second title.</h2>

Then your JavaScript could look like this:

if($('#title').is(':visible')) {
} // end if

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 an h2 on archive pages or listing pages. You'd do it like this:

<?php if(is_page() || is_single()) { ?>
  <h1><?php the_title(); ?></h1>
<?php } else { ?>
  <h2><?php the_title(); ?></h2>
<?php } // end if/else ?>

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:

<?php $tag = ( is_front_page() ) ? 'h1' : 'h2'; echo '<' . $tag . ' id="branding">'; ?>
</<?php echo $tag; ?>><!-- #branding -->

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.