1

I searched for a while but I didn't find any solution. I used the functions listed here. It outputs something like this:

Array
(
    [0] => 15
    [1] => 30
    [2] => 50
)

But I want something like this:

Array
(
    [post_id_1] => 15
    [post_id_2] => 30
    [post_id_3] => 50
)

And this is the $wp query that is used in the function:

function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) {
    global $wpdb;
    if( empty( $key ) )
        return;
    $r = $wpdb->get_col( $wpdb->prepare( "
        SELECT 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 ) );
    return $r;
}

2 Answers 2

6

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 )

2
  • When using $wpdb->prepare (reference), you don't need to quote the placeholders, i.e. p.post_status = '%s' should be p.post_status = %s.
    – Matt Sims
    Nov 20, 2018 at 19:18
  • @amit how to add orderby pm.meta_key ASC in this. I am getting error after adding this
    – Naveen
    Jan 13, 2021 at 9:57
2

WordPress have the function get_metadata this get all meta of object (Post, term, user...)

Just use

get_metadata( 'post', 15 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.