Below code list all posts with custom field “Short_Link”, sorted by the value of custom field “Comment_Count” which does not exclude any ‘post_type’ and assumes each post has just one custom field for Short_Link, and one for Comment_Count.
<?php $meta_key1 = 'Short_Link'; $meta_key2 = 'Comment_Count'; $postids = $wpdb->get_col( $wpdb->prepare( " SELECT key1.post_id FROM $wpdb->postmeta key1 INNER JOIN $wpdb->postmeta key2 ON key2.post_id = key1.post_id AND key2.meta_key = %s WHERE key1.meta_key = %s ORDER BY key2.meta_value+(0) ASC ", $meta_key2, $meta_key1 ) ); if ( $postids ) { echo "List of {$meta_key1} posts, sorted by {$meta_key2}"; foreach ( $postids as $id ) { $post = get_post( intval( $id ) ); setup_postdata( $post ); ?> <p> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </p> <?php } } ?>
Do let me know if you see any issue with this. Thanks.