もう、毎度忘れるのでメモ。
まずカスタム投稿を取得するには、post_type にカスタム投稿名を入れればOK。
カスタムタクソノミーで絞込するには、tax_query を使います。
以下の例では、カスタム投稿shopsを、カスタムタクソノミーshop_typeで絞り込みます。
対象となるタクソノミーIDは、URLのパラメータから取得することにします。
add_action( 'pre_get_posts', 'my_pre_get_posts' );
function my_pre_get_posts( $query ) {
if ( $query->is_post_type_archive('shops') && $query->is_main_query() ) {
$query->set( 'post_type', 'shops' );
$query->set( 'meta_key', 'shikuchoson_id' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'asc' );
$tax_query[] = array(
'taxonomy' => 'shop_type',
'terms' => $_GET("st"),
'field' => 'term_id',
'operator' => 'IN');
$query->set( 'tax_query', array('relation' => 'AND' , $tax_query) );
}
}
複数のカスタムタクソノミーを使って絞込には、tax_queryを複数指定します。 つまり、
$tax_query[] = array(
'taxonomy' => 'shop_type',
'terms' => $_GET("st"),
'field' => 'term_id',
'operator' => 'IN');
$tax_query[] = array(
'taxonomy' => 'shop_style',
'terms' => $_GET("ss"),
'field' => 'term_id',
'operator' => 'IN');
のようにして、$tax_queryに放り込んでやればOK
‘relation’ => ‘AND’ ではなく、’relation’ => ‘OR’にすれば、
shop_typeか、shop_styleの指定したいずれかに属するカスタム投稿を取得できます。