投稿ごとのカスタム分類のリストを得る「get_the_term_list」は特定のタームを除外したりすることができないので、これをカスタマイズした際のメモ。
get_the_term_list()は「/wp-includes/category-template.php 」に以下のように記述されている。
function get_the_term_list( $id, $taxonomy, $before = '', $sep = '', $after = '' ) {
$terms = get_the_terms( $id, $taxonomy );
if ( is_wp_error( $terms ) ) //WP_Errorオブジェクトか
return $terms;
if ( empty( $terms ) ) //空か
return false;
foreach ( $terms as $term ) {
$link = get_term_link( $term, $taxonomy );
if ( is_wp_error( $link ) )
return $link;
$term_links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
$term_links = apply_filters( "term_links-$taxonomy", $term_links );
return $before . join( $sep, $term_links ) . $after;
}
これを以下のようにカスタマイズして、特定のタームを除外できるようにする。
function get_my_term_list( $id, $taxonomy, $before = '', $sep = '', $after = '', $excludes = '', $includes= '' ) {
$terms = get_the_terms( $id, $taxonomy );
if ( is_wp_error( $terms ) )
return $terms;
if ( empty( $terms ) )
return false;
foreach ( $terms as $term ) {
$link = get_term_link( $term, $taxonomy );
if($excludes) { //$excludes(除外) が指定されていれば
//カンマを「|」に置換
$excludes = str_replace(',', '|', $excludes);
//パターンを作成
$pattern = '/' . $excludes . '/i'; //念のため大文字小文字を区別しないように指定
//パターンがマッチしなければリンクを出力
if(!preg_match($pattern, $term->slug)) { //$term->name にすれば、名前で比較できる。
$term_links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}elseif($includes) {
$includes = str_replace(',', '|', $includes);
$pattern = '/' . $includes . '/i';
//パターンがマッチしたらリンクを出力
if(preg_match($pattern, $term->slug)) {
$term_links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}else{
$term_links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
}
return $before . join( $sep, $term_links ) . $after;
}
使用例
<?php echo get_my_term_list( $post->ID, 'news_tag', ' ', ', ', '','sports, culture' ); ?>