WordPress – Query Custom Fields and Sort First In/First Out

I want to get all of a certain custom field, in this case ‘sidebar’, and sort based on first entered to last entered. I can’t find any way to do this. The only thing I can find is how to query based on a custom field value.

Also, the ‘sidebar’ custom field has image URLs in it, so I can’t sort based on the value.

Related posts

Leave a Reply

1 comment

  1. The only option you have is to write a custom query to search the wp_postmeta table and sort by the meta_id column, although this is not guaranteed to be the order that you want, it will likely be as close as you can get without additional logic (saving the date added as a separate meta field or as part of an array, and then using a custom sort):

    $sql = $wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'sidebar' AND post_id = ? ORDER BY meta_id ASC", $post->ID)
    $values = $wpdb->get_col($sql);
    foreach ($values as $value){
        echo $value; // custom field value
    }