Displaying unique class for one entry from an array of entries

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:

Read More
 echo '<li class="trendingPost" <a href=mysite.com/'.$post_name.'>'$post_title'</a><li>'

The last one having li class=”trendingPost last”

Related posts

1 comment

  1. 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:

    $top4=$wpdb->get_results('SELECT ID, post_title, post_name from `'.$wpdb->prefix.'pageviews`       
        INNER JOIN `'.$wpdb->prefix.'posts` ON `postid`=`ID` 
        ORDER BY `pageviews` DESC 
        LIMIT 4;', ARRAY_A);
    
    foreach( $top4 AS $index => $row ) {
        // Ternary to set the class when it's the last row
        $class = ( $index == ( count( $top4 ) - 1 ) ) ? ' last' : '';
        // Get the URL the right way
        $url = get_permalink( $row['ID'] );
        // Echo the results from $row, including the class / url as set above
        echo '<li class="trendingPost' . $class . '">' . 
             '<a href="' . $url . '">' . $row['post_title'] . '</a><li>';
    }
    

    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:

    echo "<li class='trendingPost{$class}"><a href="{$url}">{$row['post_title']}</a><li>';
    

Comments are closed.