Key*_*tel 53

您可以使用以下方法获得该方法:

<?php $post_slug = get_post_field( 'post_name', get_post() ); ?>
Run Code Online (Sandbox Code Playgroud)

或者你可以使用这个简单的代码:

<?php
    global $post;
    $post_slug = $post->post_name;
?>
Run Code Online (Sandbox Code Playgroud)

  • @ArtinGH你的评论是错误的,post_name确实是slug而不是帖子标题。 (2认同)

Wis*_*abs 21

如果你想从循环中获得帖子的slug,那么使用:

global $post;
echo $post->post_name;
Run Code Online (Sandbox Code Playgroud)

如果你想在循环外获得帖子的slug,那么使用:

$post_id = 45; //specify post id here
$post = get_post($post_id); 
$slug = $post->post_name;
Run Code Online (Sandbox Code Playgroud)


Yat*_*lar 16

您可以通过多种方式执行此操作,例如:

1-您可以使用Wordpress全局变量$post:

<?php 
global $post;
$post_slug=$post->post_name;
?>
Run Code Online (Sandbox Code Playgroud)

2-或者你可以使用:

$slug = get_post_field( 'post_name', get_post() );
Run Code Online (Sandbox Code Playgroud)

3-或获取完整的URL然后使用PHP函数parse_url:

$url      = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url( $url, PHP_URL_PATH );
$slug = pathinfo( $url_path, PATHINFO_BASENAME );
Run Code Online (Sandbox Code Playgroud)

我希望以上方法能帮到你.


小智 8

根据 WP Codex 执行此操作的最佳选择如下。

使用全局变量 $post:

<?php 
    global $post;
    $post_slug = $post->post_name;
?>
Run Code Online (Sandbox Code Playgroud)


hos*_*neh 7

这个简单的代码对我有用:

$postId = get_the_ID();
$slug = basename(get_permalink($postId));
echo $slug;
Run Code Online (Sandbox Code Playgroud)


Igo*_*ych 5

您可以像这样从 post 对象中检索它:

global $post;
$post->post_name;
Run Code Online (Sandbox Code Playgroud)


小智 5

Wordpress:获取帖子/页面信息

<?php 
// Custom function to return the post slug
function the_slug($echo=true){
  $slug = basename(get_permalink());
  do_action('before_slug', $slug);
  $slug = apply_filters('slug_filter', $slug);
  if( $echo ) echo $slug;
  do_action('after_slug', $slug);
  return $slug;
}
?>
<?php if (function_exists('the_slug')) { the_slug(); } ?>
Run Code Online (Sandbox Code Playgroud)