[WordPress General] 親カテゴリのテンプレートを子カテゴリに適用する方法
スマートなやり方を知ったので memo.
ほほぅ!
> I would recommend using the category_template filter – just check if the current category is an ancestor of 67:
>
> [How do I set a specific template for sub-categories? – WordPress Development Stack Exchange](https://wordpress.stackexchange.com/questions/179617/how-do-i-set-a-specific-template-for-sub-categories/179621#179621?newreg=c877ea6ca2c5449b9e525158877574bc)
`parent` という slug の親カテゴリのテンプレートが `category-parent.php` として。
“`php:functions.php
/**
* Set the parent category template to sub categories.
*/
add_filter( ‘category_template’, ‘set_parent_category_template’ );
function set_parent_category_template( $template ) {
$parent_cat = get_category_by_slug( ‘parent’ );
$parent_cat_id = $parent_cat->term_id;
if ( cat_is_ancestor_of( $parent_cat_id, get_queried_object_id() ) ) {
$template = locate_template( ‘category-parent.php’ );
}
return $template;
}
“`
使われている関数やフィルターなど。
`category_template` でテンプレートを返すとフィルターされます。
> – [Plugin API/Filter Reference/category template « WordPress Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/category_template)
ですので条件に応じて `locate_template()` を利用してテンプレートを返すようにします。
> – [関数リファレンス/locate template – WordPress Codex 日本語版](https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/locate_template)
`get_queried_object_id()` を利用して、現在クエリされているオブジェクトの ID を取得します。
> – [関数リファレンス/get queried object id – WordPress Codex 日本語版](https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/get_queried_object_id)
`cat_is_ancestor_of( $cat1, $cat2 )` で、「先祖」カテゴリーとその ID をチェックして帰ってくる真偽値を利用しています。
> – [関数リファレンス/cat is ancestor of – WordPress Codex 日本語版](https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/cat_is_ancestor_of)
これを利用すると `strpos` で親カテゴリ slug が含まれているか判定とかしなくても良いですね。