Support » Developing with WordPress » Querying Custom Posts Using an Array

  • Hi,

    On my single custom post page, I’d like to display a “More Like This” section, with up to 6 additional posts. These custom posts (of type “program”) all have an ACF checkbox with multiple possible values, and I’d like to use this to pull related posts.

    For the sake of simplicity, let’s say the ACF checkbox variable name is “colors” and possible values are “red”, “green”, “yellow”, and “blue”.

    I can get the ID of the current program, as well as an array with this program’s values for “colors”: “red”, “blue”, “yellow”.

    How do I now query all the programs and pull a list of posts that have one or more of those array values for “colors”?

    Here’s what I have so far:

    $similar = get_field( ‘colors’); /* This is returning an array for the current program’s “color” array: “red”, “green”, “blue” */

    $args = array(
        'numberposts'   => 6,
        'post_type'     => 'program',
        'post_status'   => 'publish',
        'meta_query'    => array(
            'relation'      => 'AND',
            array(
                'key'       => 'color',
                'value'     => $similar
                'compare'   => 'IN')
            )); 
    
    $more_like_this = new WP_Query ($args);
    while ($more_like_this->have_posts()) : $more_like_this->the_post();
    
                    ?>
                    <?php the_title(); ?>
                    <?php echo $star_rating ?>
    
                    <?php endwhile; 
                    wp_reset_query();
                    ?>

    I’m unable to figure out how to iterate through the array to see if it matches one of the values in $similar. I’m not getting any results. Of course, the tricky part, once I get results, is that I don’t want duplicates (as other programs may also have multiple colors in common with the current program).

    I’ve been stuck on this for days–any help would be immensely appreciated. Thank you!

    • This topic was modified 2 years, 4 months ago by  rtourtelot.
    • This topic was modified 2 years, 4 months ago by  rtourtelot.
Viewing 6 replies - 1 through 6 (of 6 total)
  • Karan NA Gupta

    (@nuancedesignstudio)

    Hi,

    If I understand correctly you could this:

    
    $more_like_this = new WP_Query ($args);
    while ($more_like_this->have_posts()) : $more_like_this->the_post();
    //get the post id of the current post in the loop
    $current_post_id = get_the_ID(); 
    
    //use the post id to retrieve its ACF colors
    $current_post_acf_colors = get_field('colors', $current_post_id);
    
    /* 
    * use $current_post_acf_colors to compare the colors to your original post's colors.
    * if the post is suitable keep a record of the id somewhere
    * at the end get the unique post ids to display
    */
    
    //rest of the code
    
    

    Regards,
    Karan

    • This reply was modified 2 years, 4 months ago by  Karan NA Gupta. Reason: typos

    Thanks so much!

    I have it working–almost. The only issue is, this is currently only returning posts that have ALL of the colors matching, rather than simply returning posts that match any of the colors in the “colors” array for the current post (i.e. “red” OR “blue”).

    I should mention that “colors” is an ACF checkbox, if that makes a difference. I think the data might be serialized, but I’m not 100% what that means.

    In any case, here’s the code:

    $current = get_the_ID();
    $similar = get_field('colors');
    
    wp_reset_postdata();
    
    // build meta_queries based on similar
    for ($i=0; $i < count($similar); $i++) {
    
       	$meta_array[] = array(
                    'key' => 'colors',
                    'value' => $similar[$i],
                    'compare' => 'LIKE'
                    );
    }
    
    // do the query
    $more_like_this = new WP_Query(array(
    	'posts_per_page'   => 6,
        'relation' => 'OR',
        'meta_query' => $meta_array
    ));
    
    ?>
    
    while ($more_like_this->have_posts()) : $more_like_this->the_post(); 
    
    the_title(); 
    echo '<br/>';
    
     endwhile; 
                    wp_reset_query();
                    ?>

    It’s so close–just not sure what I’m missing. Thanks in advance for any help!

    • This reply was modified 2 years, 4 months ago by  rtourtelot. Reason: clarification
    Karan NA Gupta

    (@nuancedesignstudio)

    Hi,

    So I am not clear about the for loop but if it works good. You may want to try the IN operator instead of LIKE.

    Regards,
    Karan

    Thanks so much, Karan. The IN operator doesn’t do the trick, unfortunately.

    Basically, the for loop is populating the $meta_array with colors to compare each post in the loop’s colors array against. I believe it may be unserializing the $similar array, as from what I’ve read, serialized arrays are being used over multiple meta entries for the ACF checkbox.

    In any case, does that preclude me from being able to use IN?

    Thanks again!

    Karan NA Gupta

    (@nuancedesignstudio)

    Hey, so can you do this (on your dev/test env) to see your $similar variable in case you haven’t already.

    echo ‘

    ' . var_dump($similar ) . '

    ‘;

    I was looking at this thread, and thought the IN may work!

    • This reply was modified 2 years, 4 months ago by  Karan NA Gupta. Reason: pre tags not printing correctly
    Moderator bcworkz

    (@bcworkz)

    You are correct, IN does not apply here. It’s used where the value argument is an array and the DB field has a single value that ought to be in the array. In your case you have a single value argument and the DB field is a serialized array. Serialized means the array is stored as a string by using a particular structured format. They are notoriously difficult to use as query criteria except by using LIKE, which is horribly inefficient. There is no other option I’m aware of, other than not using serialized arrays. That would require a separate field for each option. Good for queries, bad for storage efficiency.

    Your meta_query argument is not structured correctly. The ‘relation’ argument needs to be within the meta_query array. As it is, the default AND logic is being used and the relationship you specify is ignored. The easiest way to fix this is to move the ‘relation’ argument out from the query arguments and initialize $meta_array with it before the for(){} loop begins.

    // build meta_queries based on similar
    $meta_array = array( 'relation' => 'OR', );
    for ($i=0; $i < count($similar); $i++) { //...

    The structure you are after, using sloppy syntax, is like this:

    new WP_Query([
       posts per page => 6
       meta query => [
          relation => OR
          [ colors like red ]
          [ colors like blue ]
          [ colors like yellow ]
       ]
    ])
Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Querying Custom Posts Using an Array’ is closed to new replies.