How do i hide the <h2> if the <h1> appears

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?

Related posts

Leave a Reply

2 comments

  1. 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')) {
      $('h2').hide();
    } // 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')) {
      $('#alt-title').hide();
    } // 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.

  2. I do this in my header.php file:

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