如何在 WordPress 中获取当前页面名称? [英] How can I get the current page name in WordPress?

查看:60
本文介绍了如何在 WordPress 中获取当前页面名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用哪些 PHP 代码来检索 WordPress 主题中的当前页面名称?

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()

但是这些不适用于包含帖子条目的页面.它们都将返回最新博客条目的名称.

But these don't work for a page that contains post entries. They will all return the name of the latest blog entry.

换句话说,假设您在 WordPress 中创建了一个名为我的新闻"的页面.该页面被设置为帖子页面".向页面添加几个帖子.现在,可以使用什么 API 来检索字符串my-news"?而不是最新帖子的名称?

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?

我发现以下变量似乎有效.

I've found the following variable which seems to work.

$wp_query->queried_object->post_name

这实际上是页面名称(slug)的 URL 友好版本,这也是我正在寻找的.这是使用默认模板(二十十)测试的.我真的不确定为什么下面给出的两个变量在我的网站上不起作用.感谢 keatch 用于 print_r() 提示.

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 (Twenty Ten). I'm really not sure why the two variables given below do not work on my site. Thanks to keatch for the print_r() tip.

现在,为什么这些信息隐藏得如此之深?

Now, why is this information hidden so deep down?

推荐答案

WordPress 全局变量 $pagename 应该可供您使用.我刚刚尝试使用您指定的相同设置.

The WordPress global variable $pagename should be available for you. I have just tried with the same setup you specified.

$pagename 在文件 wp-includes/theme.php 中定义,在函数 get_page_template() 内,当然在你的页面主题文件之前调用已解析,因此可以在页面模板内的任何位置使用.

$pagename is defined in the file wp-includes/theme.php, inside the function get_page_template(), which is of course is called before your page theme files are parsed, so it is available at any point inside your templates for pages.

  • 虽然它似乎没有被记录在案,$pagename 变量只有在您使用永久链接时才会设置.我猜这是因为如果你不使用它们,WordPress 不需要页面 slug,所以它不会设置它.

  • Although it doesn't appear to be documented, the $pagename var is only set if you use permalinks. I guess this is because if you don't use them, WordPress doesn't need the page slug, so it doesn't set it up.

$pagename.

  • 这是/wp-includes/theme.php里面的代码,在无法设置$pagename时使用了你指出的解决方案:
  • This is the code inside /wp-includes/theme.php, which uses the solution you pointed out when $pagename can't be set:

--

if ( !$pagename && $id > 0 ) {
  // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
  $post = $wp_query->get_queried_object();
  $pagename = $post->post_name;
}

这篇关于如何在 WordPress 中获取当前页面名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆