I have this query:
$top4=$wpdb->get_results('SELECT post_title, post_name from `'.$wpdb->prefix.'pageviews`
INNER JOIN `'.$wpdb->prefix.'posts` ON `postid`=`ID`
ORDER BY `pageviews` DESC
LIMIT 4;', ARRAY_A);
How can I display the results of it in this format using foreach
:
echo '<li class="trendingPost" <a href=mysite.com/'.$post_name.'>'$post_title'</a><li>'
The last one having li class=”trendingPost last”
This is how, given your existing code. Note that you’ve chosen
ARRAY_A
, which will return each row as an associative array, vs the standard which returns each row as an object. If you remove that, then you’ll have to update the code.To set the class, we just set up a ternary that watches if the row number matches the count of the number of rows, and if so, creates the class to insert into the output.
Note that your code incorrectly gets the URL for the post. To do this properly, it would look like this:
And, for bonus points, you may want to learn how to write code leveraging variable interpolation. Example of how to do it, which gives you an idea of how it feels “cleaner” when reading it: