Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm occasionally facing this problem and not sure what causes it, any ideas?

<?php get_header(); ?>
    <div class="content" role="main">
            <h1><?php the_title(); ?></h1>
            <?php get_template_part( 'loop', 'index' ); ?>
    </div>
<?php get_footer(); ?>

For a normal page the_title returns "Page title".

But for a blog (using loop.php as in index file above) it returns "First posts title".

Any ideas?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

the_title is a Loop tag. It "Displays or returns the title of the current post" and it is supposed to be used inside the Loop, not outside of it.

What you are doing-- calling it outside the Loop-- is not quite correct, and you are getting inconsistent results. What happens is this:

  1. The $post variable gets set to the first post in the Loop very early in the page load. For some pages, like single posts pages which have only one post in the Loop, that means $post is "the page you are on"-- more or less. For archive pages it is the first page in the Loop. You can put var_dump($post); before wp_head runs and see that the variable is already set.
  2. Tags like the_title use that global $post variable. You have to trace it through a couple of functions to get there but eventually you get to the get_post function and you can see in the source that this is the case. In this case the chain is the_title->get_the_title->get_post

So, what you are describing is exactly what should be happening. You are using the tag incorrectly. It sometimes works the way you want only because of a quirk of the code. It isn't really supposed to work that way, or so it seems to me.

If you want "the page you are on" you will sometimes need to use get_queried_object, but watch it since it returns different kinds of data depending on the page, and for some pages returns NULL. In other cases you are better off using the is_home, is_category, etc. conditionals than you are depending on the query data like that. In fact, in most cases you are better off with those conditionals, or just with a call to wp_title as toscho suggests, but the context you are trying to use this in makes me wonder if that is correct. Plus, the output of wp_title can be, and frequently is, manipulated by plugins (SEO plugins for example), which may or may not be what you want.

share|improve this answer

On archive pages – blog, year, category and so on – use wp_title() to get the page title. the_title() relies on data of a single post.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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