Using Wp-query with serialized postmeta values

I’ve stored some serialized data in wp-postmeta table, e.g.:

$data = array(
    'details'    => $dettagli,
    'vernice'    => $vernice,
    'reperibile' => $reperibile,
    'valore2'    => $valore2,
    'valuta2'    => $valuta2,
    'subcat'     => $subcat
);

add_post_meta($post_ID, 'meta', $data);

I would like to extract all the posts with the key “details” and value = “4”. How can I do it?

Read More

I’ve tried doing this code:

$args = array(
    'post_type' => 'custom-post-type',
    'posts_per_page' => -1,
    'meta_query' => 
        array(
            'key' => 'details',
            'value' => '4',
            'compare' => 'LIKE'
        ),
    'meta_key' => 'meta',    
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
    while ($query->have_posts()) {
       $query->the_post();
       the_ID();
    }                          
}

What is wrong?

Related posts

Leave a Reply

2 comments

  1. meta_query is an array of arrays.
    You might try this:

    $args = array(
      //parameters here
      'meta_query' => array(
           array(
               'key' => 'details',
               'value' => '4',
               'compare' => 'LIKE'
           )
       ),
       //remove meta_key => 'meta'
    );
    

    however i’m not 100% sure if this could help you, let’s try it, please let me know if you get stuck.

    UPDATE

    Serialized array in post meta are not good deals. So i suggest you to change your save function to store custom fields individually.

    I’ve found a way to unserialize your previous post meta values:

    $args = array(
        'post_type'      => 'collectable',
        'meta_key'       => 'meta',
        'posts_per_page' => -1
    );
    
    $query = new WP_Query( $args );
    if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
       //Get data for each post
       $data = get_post_meta( $post->id, 'meta', true );
       //Add post meta value individually for each field
       add_post_meta( $post->ID, 'details', $data['details'] );
       add_post_meta( $post->ID, 'vernice', $data['vernice'] );
       add_post_meta( $post->ID, 'reperibile', $data['reperibile'] );
       add_post_meta( $post->ID, 'valore2', $data['valore2'] );
       add_post_meta( $post->ID, 'valuta2', $data['valuta2'] );
       add_post_meta( $post->ID, 'subcat', $data['subcat'] );
       //Delete serialized data
       delete_post_meta( $post->ID, 'meta', $data );
    
    endwhile; endif;
    

    Now you should be able to query as you want.

    Hope it helps!