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条回答
Summer. ? 凉城
2楼-- · 2019-01-05 10:25

Try this:

$pagename = get_query_var('pagename');
查看更多
唯我独甜
3楼-- · 2019-01-05 10:26

We just need to use the "post" global variable.

global $post;
echo $post->post_title;

This will echo the current page/post title.

Hope this help!!!!

查看更多
劫难
4楼-- · 2019-01-05 10:27
<?php wp_title(''); ?>

This worked for me, if I understand correctly, you want to get the page name on a page that has post entries?

查看更多
我只想做你的唯一
5楼-- · 2019-01-05 10:28

Here's my version:

$title =ucwords(str_replace('-', ' ', get_query_var('pagename')));

get_query_var('pagename') was just giving me the page slug. So the above replaces all the dashes, and makes the first letter of each word uppercase - so it can actually be used as a title.

查看更多
神经病院院长
6楼-- · 2019-01-05 10:29

I have come up with a simpler solution.

Get the returned value of the page name from wp_title(), if empty, print homepage name, otherwise echo wp_title value.

<?php $title = wp_title('',false); ?>

Remember to remove the separation with first arg and then set display to false to use as a input to the variable. then just bung the code between your heading etc. tags.

<?php if ( $title == "" ) : echo "Home"; else : echo $title; endif; ?>

Worked a treat for me and ensuring that the first is declared in the section where you wish to extract the $title, this can be tuned to return different variables.

sean@loft6.co.uk

查看更多
三岁会撩人
7楼-- · 2019-01-05 10:30

Ok, you must grab the page title BEFORE the loop.

$page_title = $wp_query->post->post_title;

Check for reference: http://codex.wordpress.org/Function_Reference/WP_Query#Properties.

Do a

print_r($wp_query)

before the loop to see all the values of $wp_query object

查看更多
登录 后发表回答