Different ways to display title

The second form can be handy too:

  • We can also use the third parameter:

    the_title( $before, $after, $echo ); 
    

    to assign the title to a variable.

    Here’s an example:

    $title = the_title( '<h1 class="entry-title">', '</h1>', false );
    
  • This can also help reducing the use of <?php ?> delimiters.

    Here’s an example from the Twenty Fifteen theme

     if ( is_single() ) :
         the_title( '<h1 class="entry-title">', '</h1>' );
     else :
         the_title( sprintf( '<h2 class="entry-title"><a href="https://wordpress.stackexchange.com/questions/239292/%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );
     endif;
    

    but there are of course various ways to get rid of such if/else parts.

    Here’s an alternative form for comparison:

    <?php if( is_single() ) : ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
    <?php else : ?>
        <h2 class="entry-title"><a href="https://wordpress.stackexchange.com/questions/239292/<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
    <?php endif; ?>
    

Leave a Comment