2

@t31os gave a very helpful response to:

getting all values for a custom field key (cross-post) by providing this function

if ( ! function_exists( 'get_meta_values' ) ) {
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;
}
}

(slightly adapted)

I need to adapt this function to retrieve not one but two columns; meta_value and post_id, both from the postmeta table and store these in an array.

I'm not knowledgeable at all with mySQL.

Any help is appreciated.

6
  • 1
    You mean SELECT pm.meta_value, pm.post_id FROM?
    – fuxia
    Commented May 30, 2013 at 19:18
  • is it that easy ? i feel silly ! Commented May 30, 2013 at 19:19
  • You need $wpdb->get_results() instead of $wpdb->get_col().
    – fuxia
    Commented May 30, 2013 at 19:21
  • @toscho now it is retuning an array with the correct number of keys but all empty values... Commented May 30, 2013 at 19:30
  • @toscho i have found the answer based on your comments; being a new member i cant answer my own question for the next few hours though; i will share my response later. Thanks for your input! Commented May 30, 2013 at 20:01

1 Answer 1

1

Following the recomendations of @toscho i had a look at get_results and the following edits to the function ended up doing the trick.

if ( ! function_exists( 'get_meta_values' ) ) {
function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) {
    global $wpdb;
    if( empty( $key ) )
        return;
    $r = $wpdb->get_results($wpdb->prepare( "
        SELECT      pm.meta_value, pm.post_id 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 ), ARRAY_A );
    return $r;
}
}

It only worked when i added the second parameter ARRAY_A (ARRAY_N or OBJECT(default) would have been possible too) to get_results() as per http://codex.wordpress.org/Class_Reference/wpdb

Thanks to everyone for their help.

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.