Blog

WordPressで複数のカスタム属性をミックスしたタグクラウドを表示する

Posted by admin at 8:00 日時 2011/02/10

WordPress3.0以降、身近になった感のあるカスタム属性(タクソノミー)。かんたんに言うと、記事につける投稿タグを自由に追加できる機能です。タグのグループ分けをしたいなというときに便利です。

今回はそんなカスタム属性を複数追加した場合に、複数のタクソノミーを横断したタグクラウドを作る方法をご紹介します。標準のwp_tag_cloud()のちょっとした改造ですので、そのうち標準で対応されるかもしれないです。

複数のカスタム属性をミックスする関数

テーマのfunctions.phpに追加してください。

function mixed_tag_cloud( $args = '' ) {  	$defaults = array(  		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,  		'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC',  		'exclude' => '', 'include' => '', 'link' => 'view', 'taxonomies' => array('post_tag'), 'echo' => true  	);  	$args = wp_parse_args( $args, $defaults );    	if ( is_array($args['taxonomies']) ) {  		foreach ( $args['taxonomies'] as $taxonomy ) {  			if ( taxonomy_exists( $taxonomy ) ) {  				$t[] = $taxonomy;  			}  		}  	} else {  		return false;  	}  	$args['taxonomies'] = $t;    	$tags = get_terms( $args['taxonomies'], array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) );    	foreach ( $tags as $key => $tag ) {  		if ( 'edit' == $args['link'] )  			$link = get_edit_tag_link( $tag->term_id, $tag->taxonomy );  		else  			$link = get_term_link( intval($tag->term_id), $tag->taxonomy );    		if ( is_wp_error( $link ) )  			return false;    		$tags[ $key ]->link = $link;  		$tags[ $key ]->id = $tag->term_id;  	}    	$return = wp_generate_tag_cloud( $tags, $args );    	$return = apply_filters( 'wp_tag_cloud', $return, $args );    	if ( 'array' == $args['format'] || empty($args['echo']) )  		return $return;    	echo $return;  }

テーマ内でタグクラウドを出力

array()の中には、タグクラウドに含めたいカスタム属性のラベルを含めてください。

<?php  if ( function_exists( 'mixed_tag_cloud' ) ) {  $args = array( 'taxonomies' => array('price','brand','option') );  mixed_tag_cloud($args);  }  ?>

これがあれば、気軽にカスタム属性を使うことができそうです


Share this entry