0

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>

1 Answer 1

2

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.

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.