1

I have a post type called usr_jardin with a custom field called sim_nuip. I would like to get the search to work for the title of the post and also by custom field . I try this but does not work me.

function searchfilter($query)
{
    $custom_fields = array("_post_title", "nuip");
    $searchterm = $query->query_vars['s'];
    $query->query_vars['s']="";

    if($searchterm != "")
    {
        $meta_query = array('relation' => 'OR');

        foreach($custom_fields as $cf)
        {
            array_push($meta_query, array('key'=> $cf,'value'=> $searchterm,'compare'=> 'LIKE'));
        }

        $query->set("meta_query", $meta_query);
    }

    if($query->is_search)
    {
        $query->set('post_type', array('post', 'usr_jardin'))
    }
    return $query;
}

add_filter('pre_get_posts','searchfilter');
add_action('save_post','add_title_custom_field');

function add_title_custom_field($postid){
    update_post_meta($postid, "_post_title", $_POST["post_title"]);
}

1 Answer 1

1

pre_get_posts is an action, not a filter. Change this:

add_filter('pre_get_posts','searchfilter');

to this:

add_action('pre_get_posts','searchfilter');

You also don't need to return $query.

See documentation for pre_get_posts: http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

1
  • You're right, but I'm pretty sure, these fixes won't make this code to work. It's not pretty, but actually you can use add_filter to Hook an action (at least for now), and of course your action function can return anything (it will be ignored). There is another problem with this code though... Take a look at his query modifications... Aug 31, 2016 at 3:56

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.