WordPress.org

Ready to get started?Download WordPress

Forums

posts_where filter to search keyword on all custom fields (1 post)

  1. tamarajane.
    Member
    Posted 2 years ago #

    Hey all,

    What I'm trying to do
    I have a custom post type which users should be able to find (among other ways) by doing a keyword search. The keyword search should test each custom field.

    What I have so far:

    $keyword = $_GET['keyword'];
    
    			// Query Arguments:
    			$args = array(
    					'post_type'=> 'myposttype',
    					'post_status' => 'publish',
    					'posts_per_page' => '-1'
    				);
    
    			$filter = 'include_custom_fields_in_search';
    			add_filter('posts_where',$filter);
    
    			query_posts($args);

    My filter function is

    //Include Custom Fields in Keyword Searches
    function include_custom_fields_in_search($where = ''){
    	$custom_fields = array(
    						 'first_name',
    					         'middle_names',
                                                     'surname'
    );
    
    	$term = $_GET['keyword'];
    
    	$where .= " AND (";
    
    	for($i=0;$i<count($custom_fields);$i++){
    
    		$where .= " (wp_postmeta.meta_key = '$custom_fields[$i]' AND 			wp_postmeta.meta_value LIKE '$term')";
    
    		$where .= (($i+1) < count($custom_fields)) ? " OR " : "" ; // on all but last, add OR 
    
    	}
    
    	$where .= " ) ";
    
    	return($where);
    
    }

    I can't workout why this doesn't return any results. I have an entry with the surname "twonk", but no entries show up. An echo of the $where comes up as:

    AND wp_posts.post_type = 'myposttype'
    AND (wp_posts.post_status = 'publish')
    AND (
    (wp_postmeta.meta_key = 'first_name' AND wp_postmeta.meta_value LIKE 'twonk')
    OR (wp_postmeta.meta_key = 'middle_names' AND wp_postmeta.meta_value LIKE 'twonk')
    OR (wp_postmeta.meta_key = 'surname' AND wp_postmeta.meta_value LIKE 'twonk')
    OR (wp_postmeta.meta_key = 'nick_name' AND wp_postmeta.meta_value LIKE 'twonk')
    )

    Can anyone see where I'm going wrong?

Topic Closed

This topic has been closed to new replies.

About this Topic