<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="s" id="s" value=" " />
<input type="text" class="field" name="custom_field_name" placeholder="キーワードを入力" />
<button type="submit" name="submit" id="searchsubmit" >検索</button>
</form>
function custom_search_query( $query ) {
if ( !is_admin() && $query->is_search ) {
$custom_field = $_GET['custom_field_name'];
if (!empty($custom_field)) {
$meta_query = array(
array(
'key' => 'your_custom_field_key',
'value' => $custom_field,
'compare' => 'LIKE'
)
);
$query->set('meta_query', $meta_query);
$query->set('post_type', 'your_custom_post_type'); // ここでカスタム投稿タイプを設定
}
}
}
add_filter( 'pre_get_posts', 'custom_search_query');
検索結果を表示するテンプレート(search.php)に検索ワードを表示する方法
<?php
if ( have_posts() ) :
$custom_field = sanitize_text_field( $_GET['custom_field'] ); // カスタムフィールドの検索ワードを取得
echo '<h2>検索ワード: ' . $custom_field . '</h2>'; // 検索ワードを表示
while ( have_posts() ) : the_post();
// 各投稿の表示処理
endwhile;
else :
echo '<p>該当する投稿が見つかりませんでした。</p>';
endif;
?>




