2

Question about a piece of PHP code in a WordPress template file.

The template contains this code:

<h1><?php the_title(); ?></h1>

I want the title only be printed if the title is not "Home".

But this code doesn't work:

<?php if (the_title()!='Home'); ?>
   <h1><?php the_title(); ?></h1>
<?php endif; ?>
2
  • you should be more clear about the problem than simply saying it "doesn't work". Tell us the error messages you're getting, or what you're seeing that is wrong. Commented Sep 4, 2012 at 12:09
  • You're right, will do that the next time, as I normally do Commented Sep 4, 2012 at 12:22

4 Answers 4

5

the_title() echoes, it doesn't return its title.

Use get_the_title() instead.

<?php if (get_the_title() != 'Home'): ?>
   <h1><?php the_title(); ?></h1>
<?php endif; ?>

As an aside, it looks like you're trying to detect if you're on the home page. Checking against a title can be flaky, as that can change.

Use is_home() instead.

<?php if ( ! is_home()): ?>
   <h1><?php the_title(); ?></h1>
<?php endif; ?>
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for a very helpful answer with lots of wordpress specifics. But you did neglect to point out the one big problem in his PHP syntax (ie the ; instead of a : on the if() line).
Thanks guys, this works. I love SO!! And you are right about detecting the home page. Unfortunately is_home() does not work for me. I set this page as "homepage" in the menu by Settings > Reading Settings > Front page displays. But no problem, text will not change and the website has to be finished by today...
Thanks to @WordpressJoomlafreelancer I changed the code to this: <?php if (!is_front_page()): ?> <h1><?php the_title(); ?></h1> <?php endif; ?>
1

<?php if (the_title()!='Home'): ?>

                              ^

Use : instead of ;

link

1 Comment

+1 for spotting the main reason it doesn't run at all. @alex's answer is more complete and more helpful wrt wordpress specifics, but he did neglect to point out this issue.
1

Or you can use

http://codex.wordpress.org/Function_Reference/is_front_page

Comments

0

Another simple solution:

<?php if (the_title()!='Home') { ?>
   <h1><?php the_title(); ?></h1>
<?php } ?>

3 Comments

This won't work - as Alex says, the_title() cannot be evaluated like that, you'd have to use get_the_title().
ok use get_the_title() with this solution and this won't work?
No, what I mean is that what you've put will work assuming you use get_the_title instead :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.