Get posts based on meta key/value

The problem

It looks like you are saving the data as:

$a = array( "13112" );
update_post_meta( $post_id, "article_author", $a);

where this will give you the meta_value

a:1:{i:0;s:5:"13112";}

Your first query will give you escaped quotes:

LIKE '%\"13112\"%'

Method 1

If you save the author array with numbers instead:

$a = array( 13112 );
update_post_meta( $post_id, "article_author", $a);

then the corresponding meta_value will be

a:1:{i:0;i:13112;}

So when you try the meta query:

 'meta_query' => array(
            array(
                'key' => 'article_author',
                'value' => ':13112;',
                'compare' => 'LIKE'
            )
    )

the corresponding SQL part will be

LIKE '%:13112;%'

You could try to use this instead.

Method 2

Another way is to remove the escaped quotes with non-escaped quotes:

add_filter('posts_where','my_posts_where');
$getPosts = new WP_Query($args);
remove_filter('posts_where','my_posts_where');

where

function my_posts_where($where){    
    $where = str_replace('\"', '"', $where);    
    return $where;  
}

but I don’t reccomend it.

Leave a Comment