我试图在循环外检索当前WordPress页面的slug。页面标题返回为wp_title ()
, 但是我怎样才能得到子弹呢?
<li>
<a href="/slug-of-current-page/">
<?php wp_title(\'\', true); ?>
</a>
</li>
我试图在循环外检索当前WordPress页面的slug。页面标题返回为wp_title ()
, 但是我怎样才能得到子弹呢?
<li>
<a href="/slug-of-current-page/">
<?php wp_title(\'\', true); ?>
</a>
</li>
使用全局变量$post
:
<?php
global $post;
$post_slug = $post->post_name;
?>
根据其他答案,slug存储在post_name
所有物虽然可以直接访问,但我更喜欢(未充分使用)get_post_field()
用于访问没有适当API的post属性的函数。
它需要显式提供post,并且不会默认为当前post,因此对于当前post,完整的post应该是:
$slug = get_post_field( \'post_name\', get_post() );
// 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;
获取slug的简单方法是:
<?php echo basename(get_permalink()); ?>
给出了代码示例,看起来您真正需要的是一个链接。在这种情况下,您可以使用get_permalink(), 可以在循环外部使用。这应该比使用post slug更可靠地完成您需要的任务。
我真的不明白为什么没有一个答案能简单地做到:
global $wp;
$current_slug = $wp->request;
// Given the URL of https://example.com/foo-bar
if ($current_slug === \'foo-bar\') {
// the condition will match.
}
这适用于所有帖子、页面和自定义路由。可能是个老问题,但我根据您的答案创建了函数get\\u the\\u slug()和the\\u 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) );
}
}
如果您想要一个更隐蔽的答案,您可以使用下面的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轻松获得正确的post表,方法如下:<?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
, 或aPDO
例子由于此查询中没有用户输入,因此只要不向其中注入任何变量,就可以在没有准备好的语句的情况下安全运行。我建议将其存储为类的私有静态值,这样就可以访问它,而无需每页多次启动查询即可获得最佳性能,类似这样:
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
}
你明白要点了。如果您需要进一步的详细信息,您可以使用new \\WP_Post( get_the_ID() );
这将使您可以随时查看帖子,即使wordpress循环没有达到您的请求可以接受的程度。这是Wordpress核心本身运行的同一查询的优化版本。这一个过滤掉了所有您不想返回的垃圾,只提供了一个组织良好的列表,其中包含相关的作者id、帖子类型、slug和可见性。如果您需要进一步的详细信息,您可以使用new \\WP_Post($id);
, 或者对任何相关的表行使用任何其他本机Wordpress函数,甚至在循环之外。
我在自己的几个自定义主题和插件中使用了类似的设置,效果非常好。它也很安全,不会让内部数据在全局范围内浮动,在全局范围内可以像Wordpress中的大多数内容那样被覆盖。
这是要在循环外部检索段塞时使用的函数。
get_post_field( \'post_name\');
在此处找到答案:How to Retrieve the Slug of Current Page in WordPress?进一步了解@Matthew Boynes answer,如果您对获取父slug(如果有)也感兴趣,那么我发现此函数很有用:
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;
}
例如,将slug添加到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\' );
如果你在循环中,那么其他答案将帮助你。如果没有(例如,您正在init
或plugins_loaded
) 您可以求助于PHP原语,如parse_url()
.
以下是一个在这两种情况下都适用的函数:
function get_the_slug() {
global $post;
$slug = $post->post_name ?? \'\';
if ( ! $slug ) {
$slug = basename( parse_url( $_SERVER[\'REQUEST_URI\'] ?? \'\', PHP_URL_PATH ) );
}
return $slug;
}
Please note 这种方法只适用于根级别的帖子/页面,因为basename()
作品WordPress中的动态页面调用。
<?php
get_template_part(\'foldername/\'.basename(get_permalink()),\'name\');
?>
我使用最新的框架框架创建了一个自定义组件,该框架需要将其URL作为当前组的一部分。我已经在组件的setup\\u nav()函数中完成了这一点,但当我尝试访问URL时,会出现404错误。我整个上午都在试图解决这个问题,但运气不好。有人能帮我指出正确的方向吗?以下是我的组件的setup\\u nav方法:function setup_nav() { $link = trailingslashit(bp_get_root_domain().\'/\'.bp_get_groups