WordPressの検索結果画面で検索した内容を取得する方法をメモ。
サンプルコード
検索フォームを以下のように作成してみます。
PHP
<form method="get" action="<?php echo home_url(); ?>"> <input type="search" name="s" id="s"> <?php $categories = get_categories(); if ( $categories ) : ?> <ul> <li> <input type="radio" name="cat" id="cat" value="" checked> すべて </li> <?php foreach ( $categories as $category ): ?> <li> <input type="radio" name="cat" value="<?php echo esc_attr( $category->term_id); ?>"> <?php echo esc_html( $category->name ); ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> <?php $tags = get_tags(); if ( $tags ) : ?> <ul> <li> <input type="radio" name="tag" id="tag" value="" checked> すべて </li> <?php foreach ( $tags as $tag ): ?> <li> <input type="radio" name="tag" value="<?php echo esc_attr( $tag->slug); ?>"> <?php echo esc_html( $tag->name ); ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> <input type="submit" id="searchsubmit" value="検索"> </form>
検索結果画面で検索した内容を取得します。
PHP
<?php
if($_GET) {
	$getStr = $_GET['s'];
	$getCat = $_GET['cat'];
	$getTag = $_GET['tag'];
	// 検索文字列
	var_dump($getStr);
	// 検索カテゴリー
	if($getCat !== '') {
		$getCatData = get_term_by( 'ID', $getCat, 'category');
		var_dump($getCatData->name);
	}
	// 検索タグ
	if($getTag !== '') {
		$getTagData = get_term_by( 'slug', $getTag, 'post_tag');
		var_dump($getTagData->name);
	}
	// 検索結果の件数
	$getCount = $wp_query->post_count;
	var_dump($getCount);
}
【参考サイト】

コメントが承認されるまで時間がかかります。