WordPress.org

Ready to get started?Download WordPress

Forums

Help on searching custom fields in a custom post type query (2 posts)

  1. jlamerto
    Member
    Posted 1 year ago #

    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?

  2. jlamerto
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic