最上位親カテゴリーidを取得する

2009.11.23

下記ソースをfunctions.phpに記載する。

<?php
function get_ctop_id($id,$visited=""){
	$visited .= '*'.$id;
	$cat = get_category($id);
	if( $cat->parent != 0 ){
		$visited .= get_ctop_id($cat->parent,$visited);
	}
	return $visited;
}
?>

以下を取得したいテンプレートの上部に記載する。

<?php
$cat = get_the_category();
$cat = $cat[0];
$cat_id = $cat->cat_ID;
// セパレート'*'の最後のひとつを取り出す
$cv_id = get_ctop_id($cat_id);$cvt_id = strrchr($cv_id,"*");$ctop_id = ltrim($cvt_id,"*");
$cat2 = get_category($ctop_id);
$cat_id = $cat2->cat_ID;
?>

表示したい箇所に下記を記載する。

<?php
print $cat_id;
?>

コメントは受け付けていません。