Custom WP Query from meta_value stored as serialised array

I’m using a Magic Fields 2 multicheck box to store Services which can be assigned to Case Studies. The data is stored as a serialised array in WordPress, and I need some help to extract the “related posts”.

I know that you can’t simply use the array as the meta_value (WordPress simply doesn’t support it) so I have to use multiple loops or add custom code within the loop.

Read More

This is the code I have so far:

<?php
$related_case_study_args = array(
    'post_type' => 'case-studies',
    'posts_per_page' => '-1',       // get all posts
);

$related_case_study_loop = new WP_Query($related_case_study_args);

if ( $related_case_study_loop->have_posts() ) : 

?>

<p>See Related Case Studies:</p>

<?php

while ( $related_case_study_loop->have_posts() ) : $related_case_study_loop->the_post();

?>

    <p class="related"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>

<?php

endwhile; endif;
wp_reset_query();

?>

which works fine and pulls in each of the Case Studies. On each Case Study, there are individual services this needs to filter by. How can I get the meta_value, extract it and only display entries which are related?

I’ve tried using this code inside the “while” statement just to see if the data is returned correctly, but without any success:

// returns an array as this is a multicheck field in Magic Fields 2
$services = get_post_meta($post->ID, 'services', true);

// foreach item in the array
foreach ($services as $service) {
    if ( sanitize_title($service_title) == sanitize_title($service) ) {
        echo '<p>' . esc_attr($service) . '</p>';

    }
}

Any help here would be appreciated!

Many thanks,

James

Related posts

Leave a Reply

1 comment

  1. If you’re inside the while loop, use get_the_ID().

    // returns an array as this is a multicheck field in Magic Fields 2
    if(get_post_meta(get_the_ID(), 'services', true)){
        $services = get_post_meta(get_the_ID(), 'services', true);
        $services = maybe_unserialize($services);
        // foreach item in the array
        foreach ($services as $service) {
            if ( sanitize_title($service_title) == sanitize_title($service) ) {
                echo '<p>' . esc_attr($service) . '</p>';
            }
        }
    } else {
        //No services set
    }
    

    Check this.
    Btw, you can set an array as a meta field value (but via code using add_post_meta, not the via post meta box on post edit screen).