WordPress custom search for custom post type

After creating a custom post type for an Inventory plugin the client needed also customized search for the columns.

Custom search for custom post type

First the pre_get_posts looked as a good candidate for hooking, but ended up with filtering via posts_clauses_request

add_filter('posts_clauses_request', 'customSearchClause');
function customSearchClause($query)
{
    global $wp_query;

    if (!is_search()) {
        return $query;
    }

    $term = $wp_query->query['s'];
    $query['join'] = 'INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)';
    $query['where'] = "AND wp_posts.post_type = '$this->post_type'
    AND (
        (wp_posts.post_title LIKE '%{$term}%')
        OR (wp_postmeta.meta_key = 'product' AND wp_postmeta.meta_value LIKE '%{$term}%')
        OR (wp_postmeta.meta_key = 'product_code' AND wp_postmeta.meta_value LIKE '%{$term}%')
    )";

    return $query;
}

Advertisements

About Michal Zuber

Full stack developer, biker and rollerblader. Owner and developer at https://nevilleweb.sk/ Co-founded http://neville.sk/ Blog at https://michalzuber.wordpress.com/
This entry was posted in Uncategorized, wordpress and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s