Switch entry titles in WordPress

featured image

Have you ever wanted to remove, or, alter the default title in a WordPress page? (Note: page not post.)
I certainly have– and, for a quick hack, I do it like this:

Find “content-page.php” in your parent theme and copy it to your child theme if your child theme doesn’t already have the file. Open “content-page.php” in your code editor of choice, and find this bit of code:

<header class="entry-header">
<?php the_title(
'<h1 class="entry-title">', '</h1>'
); ?>
	</header><!-- .entry-header -->

You can clearly see that the WordPress function the_title(); is responsible for printing the page title to the browser. What we may want to do is conditionally decide whether or not to show the default title.

We add the following code:

<header class="entry-header">

<?php if(is_page('Cats')) { ?>
<?php echo(
        '<h1 class="entry-title">My alternate title!!</h1>'
         ); ?>
     <?php } else { ?> 
		<?php the_title(
'<h1 class="entry-title">', '</h1>'
); ?>
	</header><!-- .entry-header -->

Now we are saying “If the page is titled ‘Cats’, give it a different title, else, use the default (given) title.” Right?
If you want to check for more than just one page title (e.g. Cats, Dogs, Birds and Lizards), you could use an array, like this:

<header class="entry-header">

<?php if(is_page(
                array('cats', 'dogs', 'birds','lizards')
              ) 
             ){ ?>
<?php echo(
        '<h1 class="entry-title">My alternate title!!</h1>'
         ); ?>
     <?php } else { ?> 
		<?php the_title(
'<h1 class="entry-title">', '</h1>'
); ?>
	</header><!-- .entry-header -->

To learn more about arrays, check out this post at PHP.net.

Maybe, instead of an alternate title, you want no title shown– then, in our if statement, we can remove the heading and its content, and echo nothing at all:

<?php echo( ' ' ); ?>

An edge case, perhaps, but stranger things have happened in the minds of web developers!
Though elementary, I hope you’ve found these little examples useful.

By Beau

Painter, designer (print and digital) since the twentieth century.

Leave a comment

Your email address will not be published. Required fields are marked *