How to get a meta value from all post

get_col() function returns only one column as array. To get two column result we can use get_results(), Which will return an array of objects

Which further can be converted into required structure using foreach loop.

Example –

function get_meta_values( $key = '', $type="post", $status="publish" ) {
    global $wpdb;
    if( empty( $key ) )
        return;
    $r = $wpdb->get_results( $wpdb->prepare( "
        SELECT p.ID, pm.meta_value FROM {$wpdb->postmeta} pm
        LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE pm.meta_key = '%s' 
        AND p.post_status="%s" 
        AND p.post_type="%s"
    ", $key, $status, $type ));

    foreach ( $r as $my_r )
        $metas[$my_r->ID] = $my_r->meta_value;

    return $metas;
}

( The modified version of your Example )

Leave a Comment