[WordPress General] ページやカテゴリーのスラッグを取得する

memo.

[markdown]
そういう仕組みが既にあるのかもしれないけれども、とりあえず。

> * [テンプレートタグ/get the category – WordPress Codex 日本語版](http://wpdocs.sourceforge.jp/%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%BF%E3%82%B0/get_the_category)

こんな関数を用意し、

“`php:functions.php
function the_slug() {
global $post;
if ( is_home() ) {
return ‘home’;
} elseif ( is_page() ) {
$page_slug = get_page_uri( $post->ID );
return esc_attr( $page_slug );
} elseif ( is_category() ) {
$categories = get_the_category( $post->ID );
$category_slug = $categories[0]->slug;
return esc_attr( $category_slug );
} else {
return null;
}
}
“`

こんな形で利用する。

“`php:index.php

“`

例えば、class や id を動的に変更する場合に利用する。
[/markdown]