What php code can be used to retrieve the current page name in a WordPress theme?
All the solutions I have seen so far (the_title()
, get_page()->post_name
, get_post()
, etc) don't work for a page that contains post entries. They will all return the name of the latest blog entry.
Stated another way, assume that you have a page created in WordPress with the name "My News". This page is set as the "post page". Add a couple of posts to the page. Now, what API can be used to retrieve the string "my-news" instead of the name of the latest post?
Edit:
I've found the following variable which seems to work.
$wp_query->queried_object->post_name
This is actually the URL friendly version of the page name (slug), which is what I was looking for too. This was tested with the default template (twentyten). I'm really not sure why the two variables given below do not work on my site. Thanks keatch for the print_r()
tip.
Now, why is this info hidden so deep down?
This is what I ended up using, as of 2018:
I know this is old, but I came across this and what seems to be the easiest is using this.
I believe that the Roots starter theme has a fantastic function to get the current page title, very hackable, covers all bases and can be easily used with the wp_title hook
https://github.com/roots/roots/blob/6.5.0/lib/titles.php.
I've found now in
Wordpress Codec
this function:get queried http://codex.wordpress.org/Function_Reference/wp_list_pages
which is a wrapper for
$wp_query->get_queried_object
. This post put me in the right direction but it seems that it needs this update.Show title before the loop starts:
Thank you
You can get the current page, post, or custom post type with the global variable $post.
echo $post->post_title
Note: In a function or class you'll need to specify
global $post;
prior to trying to use $post.If you have loops on your page, make sure you end each loop with
wp_reset_postdata();
to set $post back to the default item being displayed (the page).Note, the 'post_title' variable is also available for any custom loop / query.. including menu items and media attachments.. everything in WordPress is a 'post'.