bainternet
9/16/2011 - 10:10 PM

How to create Custom Taxonomy Search Drop Down for specific Post Type

How to create Custom Taxonomy Search Drop Down for specific Post Type

<?php
/*
Plugin Name: display_custom_search_form
Plugin URI: http://en.bainternet.info
Description: display_custom_search_form by shortcode
Version: 1.0
Author: Bainternet
Author URI: http://en.bainternet.info
*/


function display_custom_search_form($atts,$content = null){
    $return = '<form role="search" method="get" id="searchform" action="'.home_url( '/' ).'">
                    <div><label class="screen-reader-text" for="s">Search for:</label>
                    '.wp_dropdown_categories(array('name' =>'taxTerm', 'taxonomy' => 'TAXONOMY_NAME')).'
                        <input type="hidden" name="post_type" value="post" />
                        <input type="submit" id="searchsubmit" value="Search" />
                        <input type="hidden" name="custom_search" value="1"> 
                    </div>
                </form>';
    if ($echo){
        echo $return;
    }else{
        return $return;
    }
}

add_shortcode('my_c_s','display_custom_search_form');
add_filter('widget_text', 'do_shortcode');

//was the form submitted
if (isset($_GET['custom_search']) && $_GET['custom_search'] == 1){
    add_filter('pre_get_posts','Custom_Search_Filter');
}

 //function to actually filter the posts based on the taxonomy term and post type
function Custom_Search_Filter($query) {
    //only do this on search
    if (is_search()){
        //first check for the first type if not set then its the default post.
        $post_type = $_GET['post_type'];
        if (!$post_type) {
            $post_type = 'post';
        }
        $query->set('post_type', $post_type);

        //then check for the taxonomy term
        if (isset($_GET['taxTerm'])){
            $query->set('TAXONOMY_NAME', $_GET['taxTerm']);
        }
    }

    return $query;
}  
//usage: add [my_c_s] to your post/page/custom or text widget