WordPressにWooCommerceを入れている場合、通常の検索ウィジェットから検索した場合、post, page, productを全て表示してしまう。今日は通常検索ウィジェットから検索した時に、productとpageを表示させないコードを紹介する。functions.phpに以下のコードを入れる。
/** 検索フォームウィジェットからWooCommerce製品とWordPressページの結果を削除 */
function mycustom_modify_search_query( $query ) {
// Make sure this isn't the admin or is the main query
if( is_admin() || ! $query->is_main_query() ) {
return;
}
// WooCommerce製品検索フォームではないことを確認
if( isset($_GET['post_type']) && ($_GET['post_type'] == 'product') ) {
return;
}
if( $query->is_search() ) {
$in_search_post_types = get_post_types( array( 'exclude_from_search' => false ) );
// 削除するポストの種類(例:「product」と「page」)
$post_types_to_remove = array( 'product', 'page' );
foreach( $post_types_to_remove as $post_type_to_remove ) {
if( is_array( $in_search_post_types ) && in_array( $post_type_to_remove, $in_search_post_types ) ) {
unset( $in_search_post_types[ $post_type_to_remove ] );
$query->set( 'post_type', $in_search_post_types );
}
}
}
}
add_action( 'pre_get_posts', 'mycustom_modify_search_query' );
コメント