the_title(); works in a page template, outside the loop. Why?

Trying to wrap my head around the loop concept…

Given a template page (page-work.php) with just this code:

<?php the_title(); ?>

WP correctly shows the title of that page. As I understand it, this is outside any loop and shouldn’t work (Codex says to use get_the_title in those cases).

So the question is, why does it work?

Funnily enough, this won’t output the title + content, just the title:

<?php the_title(); the_content(); ?>

Thanks!

1 Answer
1

The global $post object exists already for singular views before wp_head is called. It is just not filled with all data.

The the_title() calls get_the_title() which in turn calls get_post(). And that calls $GLOBALS['post'] if no post ID has been passed.

See also Generating the ogp tags in theme for a use case.

Leave a Comment