WordPress: How to Search within a specific category by slug (category name)

How can I create a code which would search by slug(category name) but not by ID. How can I create a customized solution for my client for search within a specific category (without any plugins)?

Explain: I want the code of search to be customized in such a way that the client could search within a specific category without editing any code. Thanks!

Related posts

Leave a Reply

1 comment

  1. is it’s still actually, you should to check this tutorial where an author gives a very detailed explanation about the Search function customization.

    One of the most interesting parts for a necessary your case:

    // meta_query expects nested arrays even if you only have one query
    $sm_query = new WP_Query( array( 'post_type' => 'accommodation', 'posts_per_page' => '-1', 'meta_query' => array( array( 'key' => '_sm_accommodation_city' ) ) ) );
    
    // The Loop
    if ( $sm_query->have_posts() ) {
        $cities = array();
        while ( $sm_query->have_posts() ) {
            $sm_query->the_post();
            $city = get_post_meta( get_the_ID(), '_sm_accommodation_city', true );
    
            // populate an array of all occurrences (non duplicated)
            if( !in_array( $city, $cities ) ){
                $cities[] = $city;    
            }
        }
    }
    } else{
           echo 'No accommodations yet!';
           return;
    }
    
    
    /* Restore original Post Data */
    wp_reset_postdata();
    
    if( count($cities) == 0){
        return;
    }
    
    asort($cities);
    
    $select_city = '<select name="city" style="width: 100%">';
    $select_city .= '<option value="" selected="selected">' . __( 'Select city', 'smashing_plugin' ) . '</option>';
    foreach ($cities as $city ) {
        $select_city .= '<option value="' . $city . '">' . $city . '</option>';
    }
    $select_city .= '</select>' . "n";
    
    reset($cities);