Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

@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.

share|improve this question
1  
You mean SELECT pm.meta_value, pm.post_id FROM? –  toscho May 30 '13 at 19:18
    
is it that easy ? i feel silly ! –  Ronnieinspain May 30 '13 at 19:19
    
You need $wpdb->get_results() instead of $wpdb->get_col(). –  toscho May 30 '13 at 19:21
    
@toscho now it is retuning an array with the correct number of keys but all empty values... –  Ronnieinspain May 30 '13 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! –  Ronnieinspain May 30 '13 at 20:01
show 2 more comments

1 Answer

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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