Reynold
Reynold

Reputation: 51

WP_Query search by meta_key value

I have a meta field "a" with a1, a2, a11 multiplie values, etc.

get_post_meta(id, 'a'); displayed: Array array ([0] => a1 [1] => a6)

I do search by this code

array(
'key' => 'a',
'value' => 'a1',
'compare' => 'LIKE'
),

But there was a problem, LIKE does not exact search and coincidence. at a1 value records with the field a11 are also displayed. How it is possible to correct it that search was precisely on a1 to value?

'value' => 'a1',
'compare' => '='

And

'value' => array('a1'),
'compare' => 'IN'

don't work. nothing is displayed

Upvotes: 0

Views: 2298

Answers (2)

Prathak Godawat
Prathak Godawat

Reputation: 84

i think this code woring.

 $args = array(
        'post_type'  => 'my_custom_post_type',
        'meta_key'   => 'age',
        'meta_query' => array(
            array(
                'key'     => 'age',
                'value'   => array( 3, 4 ),
                'compare' => 'IN',
            ),
        ),
    );
    $query = new WP_Query( $args );

Good Luck

Upvotes: 1

Bhunesh  Satpada
Bhunesh Satpada

Reputation: 810

Use custom query via get_results.

$querystr = "
    SELECT $wpdb->posts.* 
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->postmeta.meta_key = 'a' 
    AND $wpdb->postmeta.meta_value = 'a1' 
    AND $wpdb->posts.post_status = 'publish' 
    AND $wpdb->posts.post_type = 'post'
    AND $wpdb->posts.post_date < NOW()
    ORDER BY $wpdb->posts.post_date DESC
 ";
 $pageposts = $wpdb->get_results($querystr, OBJECT);

https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

Upvotes: 0

Related Questions