如何检索当前页面的标签?
11 个回答
- 投票数
-
-
谢谢.您的解决方案效果很好.只需要回声一下:`post_name;echo $post_slug; ?>`Thank you. Your solution works great. Just need to echo the slug: `post_name; echo $post_slug; ?>`
- 4
- 2012-02-13
- sarytash
-
就像sarytash所说的,您需要"回显"它.因此,这将是理想的:`post_name;?>`Like sarytash said, you need to `echo` it. So, this'd be ideal: `post_name; ?>`
- 2
- 2013-10-11
- its_me
-
怎么样[`$ WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post)?What about [`$WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post)?
- 0
- 2019-04-24
- Peter Mortensen
-
-
- 2015-05-20
根据其他答案,段塞存储在
post_name
属性中.虽然可以直接访问它,但我更喜欢使用(未充分利用)的get_post_field()
函数来访问没有适当API的帖子属性.它需要显式提供的帖子,并且默认不为当前帖子,因此,当前帖子的全文为:
$slug = get_post_field( 'post_name', get_post() );
As per other answers, slug is stored in the
post_name
property. While it could be accessed directly, I prefer the (underused)get_post_field()
function for accessing post properties which have no proper API for them.It requires post provided explicitly and doesn't default to the current one, so in full for the current post it would be:
$slug = get_post_field( 'post_name', get_post() );
-
值得注意的是,如果您处于循环中,则可以使用没有第二个参数的`get_post_field`([docs](https://developer.wordpress.org/reference/functions/get_post_field/))It is worth noting that if you are in the loop you can use `get_post_field` without second argument ([docs](https://developer.wordpress.org/reference/functions/get_post_field/))
- 13
- 2016-06-16
- jmarceli
-
- 2015-05-21
编辑2016年4月5日
在寻求更高的可靠性之后,我最终对以下帖子进行了此答案 :(请务必将其签出)
到目前为止,我能想到的最可靠的方法是:
// Get the queried object and sanitize it $current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() ); // Get the page slug $slug = $current_page->post_name;
这样,您可以确保99.9999%的时间每次都能获得正确的数据.
原始答案
解决此问题的另一种更安全的方法是使用
可以使用get_queried_object()
,它保存当前查询的对象,以获取由post_name
属性保存的页面信息.可以在模板中的任何位置使用它.$post
,但是它可能不可靠,因为任何自定义查询或自定义代码都可以更改$post
的值,因此应避免在循环.使用
get_queried_object()
来获取当前页面对象更加可靠,并且不太可能被修改,除非您使用邪恶的query_posts
来破坏主页面查询对象,但这取决于您自己.您可以按照以下说明使用
if ( is_page() ) $slug = get_queried_object()->post_name;
EDIT 5 APRIL 2016
After digging for more reliability, I ended up doing this answer to the following post which leads to this edit: (Be sure to check it out)
The most reliable method till date I could come up with is the following:
// Get the queried object and sanitize it $current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() ); // Get the page slug $slug = $current_page->post_name;
This way, you are 99.9999% sure that you get the correct data every time.
ORIGINAL ANSWER
Another safer alternative to this problem is using
get_queried_object()
which holds the current queried object to get the page slug which is held by thepost_name
property. This can be used anywhere in your template.$post
can be used, but it can be unreliable as any custom query or custom code can change the value of$post
, so it should be avoided outside of the loop.Using
get_queried_object()
to get the current page object is much more reliable and is less likely to be modified, unless you are using the evilquery_posts
which breaks the main query object, but then that is all up to you.You can use the above as follow
if ( is_page() ) $slug = get_queried_object()->post_name;
-
我必须说,当您想更改主查询时," query_posts"并不是邪恶的***,但是您通常不这样做,并且经常被滥用:)I must say that `query_posts` is not evil ***when you want to alter the main query***, which however you usually don't and is often misused :)
- 0
- 2018-03-03
- jave.web
-
-
这取决于永久链接设置.如果您使用"简单"设置,则链接的外观将类似于" http://domain/?p=123",而剩下的则是"?p=123".this depends on the permalink settings. If you use the "simple" setting, links will look like `http://domain/?p=123`, leaving you with `?p=123`.
- 4
- 2016-10-14
- Mene
-
@Mene是对的,但是问题是如何获取段符,通常意味着URL中有一个段符(GET arg`p`不是段符).@Mene true, but question is how to get slug which, usually, means there is one in the url (GET arg `p` is not a slug).
- 1
- 2020-02-17
- jave.web
-
这是如此整洁的一线:DThis is such a neat one liner :D
- 0
- 2020-03-13
- Sean Doherty
-
-
- 2012-02-13
给出代码示例,看起来您真正需要的是一个链接.在这种情况下,您可以使用get_permalink(),可以在循环外部使用它.这比使用后更可靠地完成您需要的工作.
Given the code example, it looks like what you really need is a link. In that case, you can use get_permalink(), which can be used outside of the loop. That should do what you need more reliably than using the post slug.
-
不过,这是完整的URL,而不仅仅是段.This is the full URL though, not just the slug.
- 4
- 2014-11-21
- Fred
-
- 2017-08-29
可能是一个老问题,但是我根据您的回答创建了get_the_slug()和the_slug()函数.
if ( !function_exists("get_the_slug") ) { /** * Returns the page or post slug. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. * @return string */ function get_the_slug( $id = null ){ $post = get_post($id); if( !empty($post) ) return $post->post_name; return ''; // No global $post var or matching ID available. } /** * Display the page or post slug * * Uses get_the_slug() and applies 'the_slug' filter. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. */ function the_slug( $id=null ){ echo apply_filters( 'the_slug', get_the_slug($id) ); } }
Might be an old question, but I created the functions get_the_slug() and the_slug() based on your answers.
if ( !function_exists("get_the_slug") ) { /** * Returns the page or post slug. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. * @return string */ function get_the_slug( $id = null ){ $post = get_post($id); if( !empty($post) ) return $post->post_name; return ''; // No global $post var or matching ID available. } /** * Display the page or post slug * * Uses get_the_slug() and applies 'the_slug' filter. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. */ function the_slug( $id=null ){ echo apply_filters( 'the_slug', get_the_slug($id) ); } }
-
- 2019-04-09
老实说,我不明白为什么没有一个答案能做到:
global $wp; $current_slug = $wp->request; // Given the URL of https://example.com/foo-bar if ($current_slug === 'foo-bar') { // the condition will match. }
这适用于所有帖子,页面,自定义路线.
I honestly don't understand why none of the answers simply do:
global $wp; $current_slug = $wp->request; // Given the URL of https://example.com/foo-bar if ($current_slug === 'foo-bar') { // the condition will match. }
This works for all posts, pages, custom routes.
-
"老实说,我不明白为什么没有一个答案简单地做到了:..."可能是因为$ wp-> request包含URL的*full *路径部分,包括子文件夹***.此代码仅适用于根级别的帖子/页面."I honestly don't understand why none of the answers simply do:..." Probably because `$wp->request` includes the *full* path part of the URL, ***including sub-folders***. This code will only work on posts/pages that are at root level.
- 1
- 2020-05-08
- FluffyKitten
-
这是对这个问题的最好答案-在我尝试之前没有任何作用.This is the best answer to this question - nothing worked until I tried this.
- 0
- 2020-08-14
- Chris
-
- 2018-03-23
如果您想获得更详细的答案,则可以使用以下SQL查询随时提取所有帖子,无论是帖子,页面还是自定义分类法,即使没有钩子触发,的.
原始SQL:
SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM wp_posts WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;
即使在函数文件的第一行,甚至在
mu_plugins_loaded
或init
钩子之前,它也可以使用.@note
这是假定您具有标准数据库前缀
wp_posts
.如果您需要考虑变量前缀,则可以通过以下操作通过PHP轻松获得正确的发布表:<?php global $wpdb; $table = $wpdb->posts; $query = "SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM " . $table . " WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;"
然后使用
$wpdb
,mysqli
或PDO
实例运行.由于此查询中没有用户输入,因此只要您不向其中注入任何变量,就可以在没有准备好的语句的情况下安全运行.我建议将其存储为类的私有静态值,这样就可以访问它而不必为使最佳性能而每页多次触发查询,如下所示:
class Post_Cache { private static $post_cache; public function __construct() { //This way it skips the operation if it's already set. $this->initCache(); } public function get($id, $type = null) { if ( !(is_int( $id ) && array_key_exists( $id, self::$post_cache ) ) ) return false; } if ( !is_null( $type ) ) { //returns the specific column value for the id return self::$post_cache[$id][$type]; } //returns the whole row return self::$post_cache[$id]; } private function initCache() { if ( is_null(self::$post_cache) ) { $query = "..."; $result = some_query_method($query); //Do your query logic here. self::$post_cache = $result; { } }
用法
$cache = new \Post_Cache(); //Get the page slug $slug = $cache->get( get_the_ID(), 'slug'); if ($cache->get( get_the_ID() )) { //post exists } else { //nope, 404 'em } if ( $cache->get( get_the_ID(), 'status') === 'publish' ) { //it's public } else { //either check current_user_can('whatever_permission') or just 404 it, //depending whether you want it visible to the current user or not. } if ( $cache->get( get_the_ID(), 'type') === 'post' ) { //It's a post } if ( $cache->get( get_the_ID(), 'type') === 'page' ) { //It's a page }
您明白了要点.如果您需要更多详细信息,可以使用
new \WP_Post( get_the_ID() );
这将使您可以随时检查帖子,即使wordpress循环尚未达到您认为您的请求可以接受的程度.这是由Wordpress核心本身运行的同一查询的稍微优化的版本.这个过滤器过滤掉了您不希望返回的所有垃圾,并为您提供了一个井井有条的列表,其中列出了相关的作者ID,帖子类型,子词和可见性.如果您需要更多详细信息,则可以使用
new \WP_Post($id);
按照常规方式获取它们,或者将其他任何本机Wordpress函数与任何相关的表行一起使用,甚至不在表行之外循环.我在几个自己的自定义主题和插件中使用了类似的设置,并且效果很好.它也是安全的,不会在内部范围内浮动内部数据,就像在Wordpress中大多数内容一样可以覆盖内部数据.
If you want a more under-the-hood answer, you can use the following SQL query to fetch all of the posts that are either posts, pages, or custom taxonomies at any time, even if no hooks have fired whatsoever as of yet.
Raw SQL:
SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM wp_posts WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;
This works even on the very first line of your functions file, even prior to the
mu_plugins_loaded
orinit
hooks.@note
This is assuming you have a standard database prefix
wp_posts
. If you need to account for variable prefixes, you can obtain the correct post table through PHP pretty easily by doing the following:<?php global $wpdb; $table = $wpdb->posts; $query = "SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM " . $table . " WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;"
Then run with either
$wpdb
,mysqli
, or aPDO
instance. Since there is no user input in this query, it is safe to run without a prepared statement as long as you do not inject any variables into it.I would suggest storing this as a private static value of a class, so it can be accessed without having to fire the query again more than once per page for best performance, something like this:
class Post_Cache { private static $post_cache; public function __construct() { //This way it skips the operation if it's already set. $this->initCache(); } public function get($id, $type = null) { if ( !(is_int( $id ) && array_key_exists( $id, self::$post_cache ) ) ) return false; } if ( !is_null( $type ) ) { //returns the specific column value for the id return self::$post_cache[$id][$type]; } //returns the whole row return self::$post_cache[$id]; } private function initCache() { if ( is_null(self::$post_cache) ) { $query = "..."; $result = some_query_method($query); //Do your query logic here. self::$post_cache = $result; { } }
Usage
$cache = new \Post_Cache(); //Get the page slug $slug = $cache->get( get_the_ID(), 'slug'); if ($cache->get( get_the_ID() )) { //post exists } else { //nope, 404 'em } if ( $cache->get( get_the_ID(), 'status') === 'publish' ) { //it's public } else { //either check current_user_can('whatever_permission') or just 404 it, //depending whether you want it visible to the current user or not. } if ( $cache->get( get_the_ID(), 'type') === 'post' ) { //It's a post } if ( $cache->get( get_the_ID(), 'type') === 'page' ) { //It's a page }
You get the gist. If you need further details, you can fetch them as per normal with
new \WP_Post( get_the_ID() );
This will let your check the posts at any time, even if the wordpress loop has not hit a point where it finds your request agreeable. This is a slightly more optimized version of the same query run by the Wordpress core itself. This one filters out all of the junk you would not want returned, and just gives you a nicely organized list with the relevant author id, post type, slug, and visibility. If you need further details, you can fetch them as per normal with
new \WP_Post($id);
, or use any of the other native Wordpress functions with any of the relevant table rows, even outside of the loop.I use a similar setup in a couple of my own custom themes and plugins, and it works pretty great. It's also secure and doesn't leave internal data floating around in the global scope where it can be overridden like most stuff in Wordpress does.
-
- 2018-11-24
This is the function to use when wanting to retrieve the slug outside of the loop.
get_post_field( 'post_name');
Answer found here: How to Retrieve the Slug of Current Page in WordPress?
-
确实,但是您需要传递$post或帖子的ID作为第二个参数.Indeed, but you need to pass $post or ID of the post as a second argument.
- 0
- 2019-10-17
- trainoasis
-
- 2015-02-12
进一步@Matthew Boynes回答,如果您有兴趣获得父子弹(如果有),那么我发现此功能很有用:
function mytheme_get_slugs() { if ( $link = get_permalink() ) { $link = str_replace( home_url( '/' ), '', $link ); if ( ( $len = strlen( $link ) ) > 0 && $link[$len - 1] == '/' ) { $link = substr( $link, 0, -1 ); } return explode( '/', $link ); } return false; }
例如将子弹添加到主体类:
function mytheme_body_class( $classes ) { if ( $slugs = mytheme_get_slugs() ) { $classes = array_merge( $classes, $slugs ); } return $classes; } add_filter( 'body_class', 'mytheme_body_class' );
Just further on @Matthew Boynes answer, if you're interested in getting the parent slug (if any) also then I've found this function useful:
function mytheme_get_slugs() { if ( $link = get_permalink() ) { $link = str_replace( home_url( '/' ), '', $link ); if ( ( $len = strlen( $link ) ) > 0 && $link[$len - 1] == '/' ) { $link = substr( $link, 0, -1 ); } return explode( '/', $link ); } return false; }
Eg to add the slug(s) to the body class:
function mytheme_body_class( $classes ) { if ( $slugs = mytheme_get_slugs() ) { $classes = array_merge( $classes, $slugs ); } return $classes; } add_filter( 'body_class', 'mytheme_body_class' );
-
- 2017-02-14
WordPress中的动态页面调用.
<?php get_template_part('foldername/'.basename(get_permalink()),'name'); ?>
Dynamic Page calling in WordPress.
<?php get_template_part('foldername/'.basename(get_permalink()),'name'); ?>
我正在尝试在循环外检索当前WordPress页面的信息.页面标题以
wp_title ()
返回,但是如何获取此标签?