Skip to content
Advertisement

Limiting WordPress Search to specific blog category not working

So I’m trying to create a search form on a blog page so that it only searches the posts with the category “blog” this is the search form code I’m using:

<form  method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">

                   <input type="hidden"  name="cat" id="blog" value="7" />
                   
                    <input type="text" value="<?php echo get_search_query(); ?>" name="s" />
                    <input type="submit" value="Search" />
            </form> 

This is the search.php code:

<?php
/**
 * The template for displaying search results pages
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
 *
 * @package Scrap
 */

get_header();
?>

    <main id="primary" class="site-main">

        <?php
$s=get_search_query();
$args = array(
                's' =>$s
            );
    // The Query
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
        _e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
        while ( $the_query->have_posts() ) {
           $the_query->the_post();
                 ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
        <div class="alert alert-info">
          <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
        </div>
<?php } ?>

    </main><!-- #main -->

<?php
// get_sidebar();
get_footer();

When a query is searched, the url loads like it’s limited to the category: https://www.scraperapi.com/?cat=7&s=proxies But it still shows pages that are from outside of the category, and it doesn’t load all of the blog posts that match the search query. The search form is live at https://www.scraperapi.com/blog/ but it is display:hidden within a div called “blog-search” at the top.

Thank you so much in advance for any help offered!!

Advertisement

Answer

Try to get the query_variable “cat” with get_query_var and include the cat variable in the WP_Query as well. There is also some good info here regarding that. Currently the $args only includes the search term with variable $s.

Here is the adapted $args:

$cat = get_query_var('cat');
$s=get_search_query();
$args = array(
            's' => $s,
            'cat' => $cat
        );
//etc..

Alternatively, it’s also possible to modify the $wp_query global variable. This can be done by setting the tax_query of the $wp_query.

global $wp_query;
$tax_query[] = array(
array(
    'taxonomy' => 'cat',
    'field'    => 'id',
    'terms'    => $cat,
  )
);
$wp_query->set( 'tax_query', $tax_query );
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement