0
votes

I am busy developing a web application using WordPress. I have created a custom post with a few custom fields. When I search for post using WordPress search box only post with title that match the search string get returned. I want to add custom fields on searching domain.

I there a to search by custom field values in WordPress?

2
I have found a useful example on the codex. I use $query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue', 'meta_compare' => '!=' ) );Themba Clarence Malungani

2 Answers

1
votes

following can do

$args=array(
'post_type'=>'custom post',
'order'=>'ASC',
'orderby'=>'menu_order',
'meta_query' => array (
            array (
              'key' => 'meta-key',
              'value' => 'meta-value',
            )
          )
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo the_title();

                }
} 
wp_reset_postdata();
0
votes

To query a bunch of custom fields I found it easier to use the search filters instead.

http://codex.wordpress.org/Custom_Queries Scroll down to the "Keyword Search in Plugin Table" section for an example.

Here's a quick snippet of code form my custom 'posts_where' filter so you can get an idea:

function custom_search_where($where) {
    // put the custom fields into an array
    $customs = array('custom_field1', 'custom_field2', 'custom_field3');

    foreach($customs as $custom) {
        $query .= " OR (";
        $query .= "(m.meta_key = '$custom')";
        $query .= " AND (m.meta_value  LIKE '{$n}{$term}{$n}')";
        $query .= ")";
    }

    $where = " AND ({$query}) AND ($wpdb->posts.post_status = 'publish') ";
    return($where);
}

add_filter('posts_where', 'custom_search_where');

There's a lot more code but between the Codex example and the snippet above, it should give you a good idea.