• I am trying to get my custom search template to search for posts of custom post type “products” that also have custom fields (code, company) by using wp-query() function.

    My code is:

    $args = array(
    	'post_type'	=> 'product',
    	's'			=> $s,
    );
    query_posts( $args );
    
    if ( ! have_posts() ) {
    	$args = array(
    		'post_type'	=> 'product',
    		'meta_query'	=> array(
    		'relation'	=> 'OR',
    			array(
    				'key'     => 'code',
    				'value'   => $s,
    				'compare' => 'LIKE'
    			),
    			array(
    				'key'     => 'company',
    				'value'   => $s,
    				'compare' => 'LIKE'
    			),
    		),
    	);
    	$wp_query = new WP_Query( $args );
    }

    While the above works, its not ideal as it will only return posts with $s found in the custom fields if the keyword was not found using the standard ‘s’ search.

    I tried something like this

    $args = array(
    		'post_type'	=> 'product',
    	        's'			=> $s,
    		'relation'	=> 'OR',
    		'meta_query'	=> array(
    		'relation'	=> 'OR',
    			array(
    				'key'     => 'code',
    				'value'   => $s,
    				'compare' => 'LIKE'
    			),
    			array(
    				'key'     => 'company',
    				'value'   => $s,
    				'compare' => 'LIKE'
    			),
    		),
    	);
    	query_posts( $args );

    Which I’m hoping would return posts where the title and content of the custom post type contains $s (normal wp search) and also all posts where code or company fields also contain $s. But it doesn’t, any ideas what I’m doing wrong?

Viewing 1 replies (of 1 total)
  • Thread Starter jlamerto

    (@jlamerto)

    Not much response here. Maybe my question was wrong.
    Whats the wordpress way to search a custom post type and it’s custom fields?

Viewing 1 replies (of 1 total)
  • The topic ‘Help on searching custom fields in a custom post type query’ is closed to new replies.