0

I have a post type in called Publication. I also have few custom field in that post type such as Publication Year, Author...

I want to have a search box with 3 drop-down fields which is All Field, Publication Year, and Author. When user select on All Field, it will search everything all post in this post type, but when user select custom field like Publication Year or Author then it search only that post match with that Publication Year or Author.

I spend 3 days searching on this, but I got no luck so please help to advise me.

Thanks

0

Using pre_get_posts may work. Can you try something similar to the following and let me know if it meets your needs:

function search_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_search) {
      $query->set('post_type', array( 'post', 'movie' ) );
      //Should do some sanitation on $GET too
      if(isset($_GET['author'])){    //Change to your field dropdown name
        $query->set('meta_key', 'author'); //change to custom field name
        $query->set('meta_value', $_GET['author']);   
      }
      else if(isset($_GET['pubyear'])){    
        $query->set('meta_key', 'pubyear');
        $query->set('meta_value', $_GET['pubyear']);   
      }
    }
  }
}

add_action('pre_get_posts','search_filter');

UPDATE: May also be better to use $query->set('meta_query'), array(..)... depending on your needs

| improve this answer | |
  • Hi czerspalace, this code need to place on fanction.php, right? I am really new to wordpess, can you guide me how to use this function in wordpress template with search box, drop-down, and search button. Thanks for your help. – Saren Mar 27 '15 at 0:56
  • Sorry, @Saren yes it needs to be added to functions.php. I would need to know more about how your form looks and how the custom fields are created to help more – czerspalace Mar 27 '15 at 4:06
0

Thanks for your help. What I want exactly is like the image bellow. I need a text box that user can type key word and they also can filter by select the drop-down. In drop-down, it has custom field like Publication Year, Author...

enter image description here

| improve this answer | |
  • How did you create your custom fields? In what file is this form located? What does your form code look like so far? – czerspalace Mar 27 '15 at 21:17
  • I used Magic Field 2 plugin to create those custom field. This form is located in my template page, Publication page. – Saren Mar 27 '15 at 23:44
  • I am not familiar with that plugin, and without seeing the form code it is hard to determine what is needed to make this work – czerspalace Mar 28 '15 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.