How to get the current page name in WordPress?

2019-01-05 09:51发布

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?

19条回答
Ridiculous、
2楼-- · 2019-01-05 10:32

    $title = get_the_title($post); 
    $parent_title = get_the_title($post->post_parent);

    echo $title;
    echo $parent_title;

Hope this will help !! ;)

查看更多
登录 后发表回答