Support » Fixing WordPress » Search Custom Post Types and the Meta Boxes

  • Hey guys,

    I want to search all fields of my custom post types. So fat I am only able to search using the post title of my custom post types. I have the following script in my functions.php

    function cpt_search( $query ) {
    	if ( $query->is_search )
    		$query->set( 'post_type', array( 'leather_type', 'product', 'whats_new', 'product_category' ) );
    	return $query;

    How do I get to add my meta boxes to the search? Sucj as leather size, leather colour, etc?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi Archie22is,

    Custom meta boxes use a custom field key to store their data so you would need to know the key you are looking for to write your script. Something like this:

    $query -> set ( 'meta_key' , array ( 'leather_size', 'leather_color' ) );

    This is completely off the top of my head…I am more used to writing wp_query and not search query so I would play around with it some. You can find more information here:

    What you want to do is something like this:

    function custom_search_query( $query ) {
    	if ( $query->is_search ) {
    		$meta_query_args = array(
    				'key' => '__meta_field__',
    				'value' => $query->query_vars['s'],
    				'compare' => 'LIKE',
    		$query->set('meta_query', $meta_query_args);
    add_filter( 'pre_get_posts', 'custom_search_query');

    This only sort of works for me, though. What happens is that I get a search query like this:

    SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id) INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id) INNER JOIN wp_postmeta AS mt3 ON (wp_posts.ID = mt3.post_id) WHERE 1=1 AND (((wp_posts.post_title LIKE '%universe%') OR (wp_posts.post_content LIKE '%universe%'))) AND (wp_posts.post_password = '') AND wp_posts.post_type IN ('post', 'page', 'attachment', 'key_concepts', 'quotes', 'terms') AND (wp_posts.post_status = 'publish') AND (mt1.meta_key = '__meta_field__' AND CAST(mt1.meta_value AS CHAR) LIKE '%universe%') GROUP BY wp_posts.ID ORDER BY wp_posts.post_title LIKE '%universe%' DESC, wp_posts.post_date DESC LIMIT 0, 10

    This really doesn’t work the way I want it to, though, because the search strings have be in both the title AND the custom post meta data. I need to figure out a way to exclude the post title from the search or make that last AND an OR.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Search Custom Post Types and the Meta Boxes’ is closed to new replies.