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?
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:
$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 putvar_dump($post);
beforewp_head
runs and see that the variable is already set.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 theget_post
function and you can see in the source that this is the case. In this case the chain isthe_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 returnsNULL
. In other cases you are better off using theis_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 towp_title
as toscho suggests, but the context you are trying to use this in makes me wonder if that is correct. Plus, the output ofwp_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.On archive pages â blog, year, category and so on â use
single_cat_title()
to get the page title. Hope this helps youJust hit the same thing today, but I found a great solution:
One thing that can help you is going to
Worked in my case.