Search posts based on multiple categories WordPress

I am working on searching in wordpress i want to search text in multiple categories. here is my code

<form method="post" action="<?php bloginfo('home');?>/?ptype=catsearch" >
    <input type="text" name="searchtext" size="40" />
        <h2><?php _e('Categories:'); ?></h2>
        <select name="category[]" multiple='multiple'> 
            <option value=""><?php echo esc_attr(__('Please Select Your Choice')); ?></option> 
                <?php $categories=  get_categories('show_count=0&orderby=name&echo=0&hierarchical=true&depth=1&taxonomy=category&exclude=1'); 
                foreach ($categories as $category) {
                $option = "<option value=$category->term_id>";
                $option .= ucfirst($category->cat_name);
                $option .= '</option>';
                echo $option;
            }
            ?>
        </select>
    <input type="submit" id="searchsubmit" value="Search" name="submit"/>   
</form> 

when this foms posts on catsearch.php file i takes all categoryids in array and create url see code below. if muliple categories selected it creates url like http://abcd.com/?cat=3&cat=7&cat=8&s=dasdasDS. In this case it search the text only in last cat id. I think it overights the catids. I need if my search text found in any category then all posts should be displayed.

$categoryids = $_POST['category'];

            echo 'count is ---' .count($categoryids); 

            if($categoryids)
            {
                foreach($categoryids as $categoryid)
                {
                    $cat.=  'cat='.$categoryid.'&';
                }
                echo $cat = trim($cat, '&');
                echo '<br />';
                 $url .= '?'.$cat;

            }
if($_POST['searchtext'])
            {
                echo 'searchtext---'. $_POST['searchtext'];
                echo '<br />';
                $url .= '&s='.$_POST['searchtext'];
            } 
<META http-equiv="refresh" content="1;URL=<?php echo get_bloginfo('url')."$url"; ?>">

Related posts

Leave a Reply

1 comment

  1. When you are doing something like this

    cat=3&cat=7&cat=8
    

    You are constantly redefining the value of $_GET[‘cat’]. So it makes perfect sense that it would end up being the last one – 8.

    The syntax for querying multiple categories in wordpress is using a comma

    cat=3,7,8