Wordpress - the_title() shows title of the first post instead of the page title?

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.


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.

Tags:

Title

Loop