WordPress widget カスタマイズ
デフォルトテーマ等で、ウィジェットに特定カテゴリの記事リストを追加する。
実装の方法は、テキストウィジェットを追加して、
[get_my_posts slug="slug名" taxonomy="タクソノミー名"]
このようにショートコードを記載するように出来ると手軽かと思う。
デフォルトでは、ウィジェット内にショートコードは記載出来ないので、
add_filter('widget_text', 'do_shortcode');
を追加する。
function.phpに以下のコードを追加。
if(!function_exists("_get_posts_specific")):
function _get_posts_specific($atts) {
/*
* extractを使って配列で渡されるパラメータを変数に格納。デフォルトの値もここで設定
*/
extract( shortcode_atts( array(
'slug' => 'undefined',
'taxonomy' => 'category',
'num' => 5,
), $atts ) );
$output = "";
$args = array(
'posts_per_page' => $num,
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => array( $slug )
),
),
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$query = new WP_Query( $args );
$myposts = $query->posts;
/*
* HTML出力部分。
*/
if(!empty($myposts)){
$output .= '<ul class="">';
foreach ($myposts as $key => $value) {
$output .= '<li class="cat-item"><a href="' . get_permalink($value->ID) . '">' . $value->post_title . '</a></li>';
}
$output .= "</ul>";
}
return $output;
}
endif;
add_shortcode( 'get_my_posts', '_get_posts_specific' );
/*
* このad_filterがウィジェット内でショートコードを使用可能にする。
*/
add_filter('widget_text', 'do_shortcode');
これで、例えば「レストラン」というタグが付いている記事一覧は、
[get_my_posts slug="restaurant" taxonomy="post_tag"]
というふうにゲット出来ます。