How to Get Post IDs by Meta Key & Meta Value?

Are you having trouble getting post ids by meta key and value? Here is the code snippet:

<?php

if (!function_exists('get_post_ids_by_meta_key_and_value')) {
    function get_post_ids_by_meta_key_and_value($key, $value) {
        global $wpdb;

        $meta = $wpdb->get_results("SELECT post_id FROM `".$wpdb->postmeta."` WHERE meta_key='".$wpdb->escape($key)."' AND meta_value='".$wpdb->escape($value)."'");

        $post_ids = [];
        foreach( $meta as $m ) {
            $post_ids[] = $m->post_id;
        }

        return $post_ids;
    }
}

Enjoy 🙂

Leave a Reply

%d bloggers like this: