How to use IN array properly in WordPress?

I have an array containting these values (including the apostrohpes):

'course_3202','course_3201','course_3200','course_3199'

I try to fetch results from these values in postmeta-table.

Read More
SELECT * FROM wp_postmeta WHERE meta_key IN (%s) and meta_value=1

I get no result (yes, there is data and I should get results)

RESULT = Array ( )

My code looks like this:

function get_count_courses_array(array $courseids) {    
    $tmp = array();
    foreach($courseids as $cid) {
        $tmp[] = "'" . $cid . "'";
    }    
    $courseids = implode(',',$tmp);

    global $wpdb;
    $sql = "SELECT * FROM $wpdb->postmeta";
    $sql .= " WHERE meta_key IN (%s) and meta_value=1";        
    $result = $wpdb->get_results($wpdb->prepare( $sql, $courseids));

    return $result;    
}

In phpMyAdmin I tried the same and I do get results (as expected):

SELECT * FROM wp_postmeta WHERE meta_key IN ('course_3202','course_3201','course_3200','course_3199') and meta_value=1

What am I doing wrong?

Related posts

Leave a Reply

2 comments

  1. You need to have your replacement placeholders matching the number of values in your array, and then you can use the array as one of the prepare arguments.

    Proof of concept:

    $a = array('course_3202','course_3201','course_3200','course_3199');
    
    $b = array_fill(0,count($a),'%s');
    $b = implode(',',$b);
    
    $sql = "SELECT * FROM $wpdb->postmeta";
    $sql .= " WHERE meta_key IN ({$b}) and meta_value=1";    
    
    var_dump($wpdb->prepare($sql,$a));
    
  2. You are querying to postmeta table so I would use WP_Query class and methods instead:

    $courseids = array( 'course_3202', 'course_3201', 'course_3200', 'course_3199' );
    $meta_query = array();
    
    foreach( $courseids as $courseid ){
        $meta_query[] = array( 
                                  'key'   => $courseid,
                                  'value' => '1',
                                  'compare' => 'IN',
                             );
    }   
    
    $args = array(
        'post_type' => 'post',
        'meta_query' => array(
                           $meta_query
                   )
    );
    $query = new WP_Query( $args );
    
    $count_courses = $query->found_posts;