如何在 WordPress 中获取当前页面名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4837006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:42:54  来源:igfitidea点击:

How can I get the current page name in WordPress?

wordpresswordpress-theming

提问by Bernard

What PHP code can be used to retrieve the current page name in a WordPress theme?

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

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.

到目前为止the_title(),我看到的所有解决方案(、get_page()->post_nameget_post()等)都不适用于包含帖子条目的页面。它们都将返回最新博客条目的名称。

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?

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



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

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

Now, why is this information hidden so deep down?

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

回答by AJJ

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

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

$pagenameis 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定义在文件 wp-includes/theme.php 中的 function 中get_page_template(),当然在解析页面主题文件之前调用它,因此它可以在页面模板中的任何位置使用。

  • Although it doesn't appear to be documented, the $pagenamevar 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.

  • $pagenameis not set if you use the page as a static front page.

    • This is the code inside /wp-includes/theme.php, which uses the solution you pointed out when $pagenamecan't be set:

      $pagename = get_query_var('pagename'); 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; }

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

  • $pagename如果您将该页面用作静态首页,则不会设置。

    • 这是/wp-includes/theme.php里面的代码,在$pagename无法设置时使用你指出的解决方案:

      $pagename = get_query_var('pagename'); if ( !$pagename && $id > 0 ) { // 如果将静态页面设置为首页,则不会设置 $pagename。从查询对象中检索它 $post = $wp_query->get_queried_object(); $pagename = $post->post_name; }

回答by goksel

My approach to get the slug name of the page:

我获取页面 slug 名称的方法:

$slug = basename(get_permalink());

回答by keatch

Ok, you must grab the page title beforethe loop.

好的,您必须在循环之前获取页面标题。

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

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

检查参考:http: //codex.wordpress.org/Function_Reference/WP_Query#Properties

Do a

做一个

print_r($wp_query)

before the loop to see all the values of the $wp_queryobject.

在循环之前查看$wp_query对象的所有值。

回答by GregB

<?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.

如果我理解正确,您希望在具有帖子条目的页面上获取页面名称。

回答by James

You can get the current page, post, or custom post type with the global variable $post:

您可以使用全局变量获取当前页面、帖子或自定义帖子类型$post

echo $post->post_title

Note: In a function or class you'll need to specify global $post;prior to trying to use $post.

注意:在函数或类中,您需要global $post;在尝试使用$post.

If you have loops on your page, make sure you end each loop with wp_reset_postdata();to set $postback to the default item being displayed (the page).

如果页面上有循环,请确保在每个循环结束时wp_reset_postdata();设置$post回显示的默认项目(页面)。

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'.

请注意,“post_title”变量也可用于任何自定义循环/查询……包括菜单项和媒体附件……WordPress 中的所有内容都是“帖子”。

回答by Tom Auger

If you're looking to access the current page from within your functions.php file (so, beforethe loop, before $postis populated, before $wp_queryis initialized, etc...) you really have no choice but to access the server variables themselves and extract the requested page from the query string.

如果您想从您的functions.php 文件中访问当前页面(因此,循环之前$post、填充之前$wp_query、初始化之前等...),您真的别无选择,只能访问服务器变量本身,并且从查询字符串中提取请求的页面。

$page_slug = trim( $_SERVER["REQUEST_URI"] , '/' )

Note that this is a "dumb" solution. It doesn't know, for instance that the page with the slug 'coming-soon' is also p=6. And it assumes that your permalink settings are set to pagename(which they should be anyway!).

请注意,这是一个“愚蠢”的解决方案。例如,它不知道带有 slug 'coming-soon' 的页面也是p=6. 它假定您的永久链接设置已设置为pagename(无论如何都应该如此!)。

Still, can be a useful little trick if you have a controlled scenario. I'm using this in a situation where I wish to redirect non-logged in visitors to a "coming soon" page; but I have to make sure that I'm not throwing them into the dreaded "redirect loop", so I need to exclude the "coming soon" page from this rule:

尽管如此,如果您有一个受控的场景,这可能是一个有用的小技巧。我在希望将未登录的访问者重定向到“即将推出”页面的情况下使用它;但我必须确保我没有将它们扔进可怕的“重定向循环”中,所以我需要从这个规则中排除“即将推出”页面:

global $pagenow;
if (
        ! is_admin() &&
        'wp-login.php' != $pagenow &&
        'coming-soon' != trim( $_SERVER["REQUEST_URI"] , '/' ) &&
        ! is_user_logged_in()
){
   wp_safe_redirect( 'coming-soon' );
}

回答by Sy Holloway

I believe that the Roots starter themehas a fantastic function to get the current page title. It is very hackable, covers all bases, and can be easily used with the wp_titlehook.

我相信Roots starter 主题有一个很棒的功能来获取当前页面的标题。它非常易于破解,涵盖所有基础,并且可以轻松地与wp_title钩子一起使用。

/**
 * Page titles
 */
function roots_title() {
  if (is_home()) {
    if (get_option('page_for_posts', true)) {
      echo get_the_title(get_option('page_for_posts', true));
    } else {
      _e('Latest Posts', 'roots');
    }
  } elseif (is_archive()) {
    $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
    if ($term) {
      echo $term->name;
    } elseif (is_post_type_archive()) {
      echo get_queried_object()->labels->name;
    } elseif (is_day()) {
      printf(__('Daily Archives: %s', 'roots'), get_the_date());
    } elseif (is_month()) {
      printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
    } elseif (is_year()) {
      printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
    } elseif (is_author()) {
      $author = get_queried_object();
      printf(__('Author Archives: %s', 'roots'), $author->display_name);
    } else {
      single_cat_title();
    }
  } elseif (is_search()) {
    printf(__('Search Results for %s', 'roots'), get_search_query());
  } elseif (is_404()) {
    _e('Not Found', 'roots');
  } else {
    the_title();
  }
}

回答by Rahul Balakrishna

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

我们只需要使用“post”全局变量:

global $post;
echo $post->post_title;

This will echo the current page/post title.

这将回显当前页面/帖子标题。

回答by Tech1337

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 the wp_title() value.

从 wp_title() 获取页面名称的返回值。如果为空,则打印主页名称,否则回显 wp_title() 值。

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

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

请记住使用第一个参数删除分隔符,然后将 display 设置为 false 以用作变量的输入。然后在你的标题等标签之间插入代码。

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

It 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.

它对我有用,并确保第一个在您希望提取 的部分中声明$title,这可以调整以返回不同的变量。

回答by Mohammad Sabbagh

Try this:

尝试这个:

$pagename = get_query_var('pagename');