Retrieving custom fields with $wpdb->get_results

Note, before going further: Take care about portability and security:

function wpse50056_get_post_meta()
{
    global $wpdb;

    $results = $wpdb->get_results( "
        SELECT 
            ID, 
            post_date, 
            post_title, 
            post_content, 
            meta_key, 
            meta_value
        FROM {$wpdb->posts} 
            INNER JOIN {$wpdb->postmeta} 
        ON ( $wpdb->posts.ID = {$wpdb->postmeta}.post_id )
    " );

    foreach( $results as $result )
    {
        printf( '<pre>%s</pre>', htmlspecialchars( var_export( $result, true ) ) );
    }
}
add_action( 'shutdown', 'wpse50056_get_post_meta' );

Leave a Comment