WordPress 获取指定ID或当前文章别名的方法代码

WordPress教程 1732

wordpress 可以通过 the_title() 函数获取文章标题,但是却找不到能直接获取文章别名的 wordpress 函数,所以要想调用文章别名就只能编写调用函数了,代码比较简单。

把下面的代码放在主题的functions.php文件

1
2
3
4
5
6
function the_slug($postid = null) {
    if($postid == 'null') $postid = $post->ID;
    $postData = get_post($postid, ARRAY_A);
    $post_slug = $postData['post_name'];
    return $post_slug; 
}

在single.php调用当前文章的别名:

1
<?php echo the_slug();?>

调用指定文章ID为20的文章别名

1
<?php echo the_slug(20);?>

上面的代码也适用于获取单篇页面的别名。

精品推荐: