• Resolved weweloo

    (@weweloo)



    I have registered metadata for my posts, and the metadata is an array containing numeric elements, for example, [1, 3, 5]. I need to use WP_Query to retrieve a list of posts based on the condition that this metadata array includes a specified value, such as 5. However, the code I’ve written is not successfully fetching the post data, and I’m not sure where the issue lies. I hope you can help me take a look.

    $query_args =  array(
      'post_type'  => 'work',
      'posts_per_page' => 10,
      'meta_query' => array(
        array(
          'key' => 'meta_key',
          'value' => 5,
          'compare' => '=',
        ),
      ),
    );
    
    $query = new WP_Query($query_args);
Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter weweloo

    (@weweloo)

    change to ‘compare’ => ‘LIKE’ resolved.

    Moderator bcworkz

    (@bcworkz)

    I’m glad you found a solution, but FWIW LIKE queries aren’t very efficient. Depending on the size of your DB and the nature of your query, it may not make any noticeable difference. You might try this instead:

        array(
          'key' => 'meta_key',
          'value' => '5',
          'compare' => '=',
        ),

    Added quotes to 5, making it a string value instead of integer. All WP meta values are always saved as string values, even if they were initially sourced as integers. The meta_value DB field’s type is VARCHAR. If this even works, it’d be better than a LIKE query.

    Another possibility would be:

        array(
          'key' => 'meta_key',
          'value' => 5,
          'compare' => '=',
          'type' => 'NUMERIC',
        ),

    This type casts the saved value to an integer. Or you can ignore all of this due to the “if it works don’t fix it” maxim ??

    Thread Starter weweloo

    (@weweloo)

    I tried your method, but still couldn’t get the results. I switched to using a database query approach, and that allows for precise matching.

    global $wpdb;
    $sql = "SELECT post_id FROM $wpdb->postmeta 
      WHERE meta_key='meta_key' 
      AND meta_value like '%:" . esc_sql($post_id)  . ";%'";
    $found_posts = $wpdb->get_col($sql);
    if (empty($found_posts)) $found_posts = [0];
    $query_args = array(
      'post_type' => 'work',
      'post_status' => 'publish',
      'posts_per_page' => 10,
      'post__in' => $found_posts
    );
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘The issue with using WP_Query’ is closed to new replies.