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

发布于 2024-10-15 01:39:27 字数 817 浏览 4 评论 0原文

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

到目前为止我见过的所有解决方案:

  • the_title()
  • get_page()->post_name
  • get_post()
  • 等。

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

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


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

$wp_query->queried_object->post_name

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

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

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.

But these 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?


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 keatch for the print_r() tip.

Now, why is this information hidden so deep down?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

北方的巷 2024-10-22 01:39:28

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

global $post;
echo $post->post_title;

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

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

global $post;
echo $post->post_title;

This will echo the current page/post title.

野味少女 2024-10-22 01:39:28

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

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

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

不过,如果你有一个受控的场景,这可能是一个有用的小技巧。我在希望将未登录的访问者重定向到“即将推出”页面的情况下使用此功能;但我必须确保我不会将它们放入可怕的“重定向循环”中,因此我需要从该规则中排除“即将推出”页面:

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

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

$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!).

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' );
}
×纯※雪 2024-10-22 01:39:28

我相信 Roots 入门主题 有一个非常棒的函数获取当前页面标题。它非常容易破解,涵盖所有基础,并且可以轻松地与 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();
  }
}

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

/**
 * 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();
  }
}
看轻我的陪伴 2024-10-22 01:39:28

试试这个:

$pagename = get_query_var('pagename');

Try this:

$pagename = get_query_var('pagename');
弃爱 2024-10-22 01:39:28

我想出了一个更简单的解决方案。

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

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

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

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

它对我来说是一种享受,并确保第一个在您希望提取 $title 的部分中声明,可以调整它以返回不同的变量。

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.

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

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

情魔剑神 2024-10-22 01:39:28

使用:

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

echo $title;
echo $parent_title;

Use:

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

echo $title;
echo $parent_title;
小兔几 2024-10-22 01:39:28

这似乎是最容易使用的:

<?php single_post_title(); ?>

This seems to be the easiest to use:

<?php single_post_title(); ?>
路弥 2024-10-22 01:39:28

在循环开始之前显示标题:

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

Show the title before the loop starts:

$page_title = $wp_query->post->post_title;
孤凫 2024-10-22 01:39:28

如果您正在寻找实际查询的页面,而不是页面 ID 或 slug,一种选择是拦截查询:

add_action('parse_request', 'show_query', 10, 1);

在您的函数中,您可以访问 $wp 对象,并且可以获得页面名称或帖子名称与:

function show_query($wp){
     if ( ! is_admin() ){ // heck we don't need the admin pages
         echo $wp->query_vars['pagename'];
         echo $wp->query_vars['name'];
     }
}

另一方面,如果您确实需要发布数据,那么获取它的第一个地方(可以说在这种情况下,最好的地方)是:

add_action('wp', 'show_page_name', 10, 1);

function show_page_name($wp){
     if ( ! is_admin() ){
        global $post;
        echo $post->ID, " : ", $post->post_name;
     }
}

最后,我意识到这可能不是OP的问题,但是如果您如果要查找管理页面名称,请使用全局$pagenow

One option, if you're looking for the actual queried page, rather than the page ID or slug is to intercept the query:

add_action('parse_request', 'show_query', 10, 1);

Within your function, you have access to the $wp object and you can get either the pagename or the post name with:

function show_query($wp){
     if ( ! is_admin() ){ // heck we don't need the admin pages
         echo $wp->query_vars['pagename'];
         echo $wp->query_vars['name'];
     }
}

If, on the other hand, you really need the post data, the first place to get it (and arguably in this context, the best) is:

add_action('wp', 'show_page_name', 10, 1);

function show_page_name($wp){
     if ( ! is_admin() ){
        global $post;
        echo $post->ID, " : ", $post->post_name;
     }
}

Finally, I realize this probably wasn't the OP's question, but if you're looking for the Admin page name, use the global $pagenow.

私野 2024-10-22 01:39:28

WordPress Loop 中:

if ( have_posts() ) : while ( have_posts() ) : the_post();
/******************************************/
echo get_the_title();
/******************************************/
endwhile; endif;

这将显示当前页面标题。

仅供参考:get_the_title()

Within the WordPress Loop:

if ( have_posts() ) : while ( have_posts() ) : the_post();
/******************************************/
echo get_the_title();
/******************************************/
endwhile; endif;

This will show you the current page title.

For reference: get_the_title()

爱冒险 2024-10-22 01:39:28

这是我的版本:

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

get_query_var('pagename') 只是给我页面slug。因此上面替换了所有破折号,并使每个单词的第一个字母大写 - 所以它实际上可以用作标题。

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.

紅太極 2024-10-22 01:39:28

截至 2018 年,这是我最终使用的:

<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">

This is what I ended up using, as of 2018:

<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">
作妖 2024-10-22 01:39:28

我现在在WordPress Codec上找到了这个函数,

得到查询< /a>

这是 $wp_query->get_queried_object 的包装器。

这篇文章让我找到了正确的方向,但似乎需要此更新。

I've now found this function on WordPress Codec,

get queried

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.

∞梦里开花 2024-10-22 01:39:28

如果您在functions.php 中,这也适用。这不是最好的方法,因为您必须使用全局数组,但它确实有效。

  1. 首先,我们需要添加一个过滤器。必须存在比 template_include 更好的过滤器,但我不知道所有这些过滤器。请指出我正确的位置。

    add_filter( 'template_include', 'var_template_include', 1000 );
    函数 var_template_include( $template ){
        全局 $wp_query;
        $GLOBALS['current_page'] = $wp_query->get_queried_object()->post_name;
        返回$模板;
    }
    
  2. 避免直接使用变量

    function get_current_page( $echo = false ) {
        if( !isset( $GLOBALS['current_page'] ) )
            返回假;
        返回 $GLOBALS['current_page'];
    }
    
  3. 现在您可以在functions.php的任何其他部分使用函数get_current_page()

This also works if you are in the functions.php. It is not the best approach since you have to use the global array, but it works.

  1. First, we need to add a filter. There must exist a better filter to use than the template_include, but I don't know all of them. Please point me to the right one.

    add_filter( 'template_include', 'var_template_include', 1000 );
    function var_template_include( $template ){
        global $wp_query;
        $GLOBALS['current_page'] = $wp_query->get_queried_object()->post_name;
        return $template;
    }
    
  2. Avoid using the variable directly

    function get_current_page( $echo =  false ) {
        if( !isset( $GLOBALS['current_page'] ) )
            return false;
        return $GLOBALS['current_page'];
    }
    
  3. Now you can use the function get_current_page() in any other part of the functions.php.

窗影残 2024-10-22 01:39:27

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

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

  • 虽然似乎没有记录,但仅当您使用永久链接时才会设置 $pagename var。我想这是因为如果您不使用它们,WordPress 就不需要页面 slug,因此不会对其进行设置。

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

  • 这是 /wp-includes/theme.php 中的代码,它使用您在无法设置 $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;
}

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

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

  • 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 is 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 $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;
}
哆啦不做梦 2024-10-22 01:39:27

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

$slug = basename(get_permalink());

My approach to get the slug name of the page:

$slug = basename(get_permalink());
属性 2024-10-22 01:39:27
<?php wp_title(''); ?>

这对我有用。

如果我理解正确的话,您想要获取包含帖子条目的页面上的页面名称。

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

临风闻羌笛 2024-10-22 01:39:27

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

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

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

在循环之前执行一次

print_r($wp_query)

以查看 $wp_query 对象的所有值。

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

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

Check for the 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 the $wp_query object.

つ可否回来 2024-10-22 01:39:27

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

echo $post->post_title

注意:在函数或类中,您需要指定 global $post; > 在尝试使用 $post 之前。

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文