Frage

I have created a custom table which stores 'post likes' in WordPress.

$sql[] = "CREATE TABLE IF NOT EXISTS {$table_prefix}like (
    id bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    post_id bigint(20) NOT NULL,
    user_id bigint(20) NOT NULL,
        KEY recommenders (post_id, user_id)
) {$charset_collate};";

When a user clicks on a 'like' button on a WordPress post, a row gets added to the table which captures the user's ID and the post ID.

To get an array of all user IDs that have 'liked' a particular post I can do this:

$result = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM {$table_prefix}like WHERE post_id = %d", $post_id ) );

I'd now like to do 2 things:

  1. How can modify my query so that most recent rows added to the table are returned first in the $result array?

  2. How can I do exactly the same as question 1 but return 5 rows only?

War es hilfreich?

Lösung

For 1: You can order them by your id in descending order by adding ORDER BY `id` DESC to the query.

For 2: Add LIMIT 0, 5 aswell:

$result = $wpdb->get_col( $wpdb->prepare( "SELECT `user_id` FROM `{$table_prefix}like` WHERE `post_id` = %d ORDER BY `id` DESC LIMIT 0, 5", $post_id ) );

Andere Tipps

  1. To ensure the ORDER BY as ccKep alluded to I would add a LikeDate Column to your Table as a DateTime(TimeStamp)and then use the ORDER BY on the LikeDate Column. This ensures that you count the return visitors, who may REALLY LIKE the post.
  2. See the FOUND_ROWS Function, in case you want to know the total that would have been returned without the limit
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top