How to order list according to the value of variable? (php) <p>First question to the people who know wordpress well: resource/system load wise is it better to query mysql directly and order result there? or use wordpress hooks WP_query fetch all posts and order them according to comments variable?</p> <p>I've this code, it fetches everything. I'd like to order this list according to <code>comments_number( '0', '1', '%' );</code> (higher commented ones at the top) and limit total number displayed to top 4.</p> <p>My code so far:</p> <pre><code> &lt;ul&gt; &lt;?php global $post; $all_events = tribe_get_events( array( 'eventDisplay'=&gt;'upcoming', 'posts_per_page'=&gt;-1 ) ); foreach($all_events as $post) { setup_postdata($post); ?&gt; &lt;li&gt; &lt;a title="&lt;?php the_title(); ?&gt;" href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php if ( has_post_thumbnail () ) { echo get_the_post_thumbnail(array(100,100)); } else { echo '&lt;img width="100" height="100" alt="' .get_the_title().'" title="' .strip_tags(get_the_excerpt()).'" src="' .get_bloginfo('template_url') .'/thumbs/event-recent-thumb-na.png"&gt;'; } ?&gt; &lt;/a&gt; &lt;h3&gt;&lt;a title="&lt;?php the_title(); ?&gt;" href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;span&gt;&lt;?php echo tribe_get_start_date( $p-&gt;ID, true, 'M j, D.' ) . " - " . tribe_get_end_date( $p-&gt;ID, true, 'D.' ); ?&gt;&lt;/span&gt; &lt;p&gt;&lt;?php echo strip_tags(get_the_excerpt()); ?&gt;&lt;/p&gt; &lt;span class="eventinterested"&gt;&lt;?php comments_number( '0', '1', '%' ); ?&gt; &lt;?php _e('interested so far','holidayge'); ?&gt;&lt;/span&gt; &lt;/li&gt; &lt;?php } //endforeach ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/ul&gt; </code></pre> <p>Is there a way to modify <code>foreach</code> and order list there? I'm not php programmer, but it seems logical... I'm reading about <a href="http://php.net/manual/en/function.sort.php" rel="nofollow">Sort</a> seems like correct solution?</p>