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.

I was looking for a way to display a list of custom field from across all the posts on a custom made page template and I got the solution in this thread,.

As all the custom field values are strings only, I need the list to display in an alphabetical order. Is it possible ? Given is the code I am using currently that fetches me a nice unordered list, that gets the work done. If this is possible, Please suggest the change in code.

<?php
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;
}
?>
<?php $my_list_items = get_meta_values( 'full_name' ); ?>
    <h3>Display a list of custom values :</h3>
    <ul>
        <?php foreach($my_list_items as $my_list_item) {
            echo '<li>' .$my_list_item. '</li>';
            } ?>
    </ul>
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

What if you use ORDER BY pm.meta_value ASC in WP db class:

$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'
        ORDER BY pm.meta_value ASC
        ", $key, $status, $type ) );

That will provide you an ASCending ordered array.

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.