Lấy danh sách bài viết vừa xem (ok)

<?php
function wpse_63266_update_recently_viewed() {
  /**
   *  If is admin or isn't single, then return.
   *  To get only singular video posts use; if(!is_singular('videos')) return;
   */
  if (is_admin() || !is_single()) {
    return;
  }
  global $post;
  // Get the current post id.
  $current_post_id = get_the_ID();
  if (is_user_logged_in()) {
    // Store recently viewed post ids in user meta.
    $recenty_viewed = get_user_meta(get_current_user_id(), 'recently_viewed', true);
    if ('' == $recenty_viewed) {
      $recenty_viewed = array();
    }
    // Prepend id to the beginning of recently viewed id array.(http://php.net/manual/en/function.array-unshift.php)
    array_unshift($recenty_viewed, $current_post_id);
    // Keep the recently viewed items at 5. (http://www.php.net/manual/en/function.array-slice.php)
    $recenty_viewed = array_slice($recenty_viewed, 0, 5); // Extract a slice of the array
    // Update the user meta with new value.
    update_user_meta(get_current_user_id(), 'recently_viewed', $recenty_viewed);
  } else {
    /**
     * For non-logged in users you can use the same procedure as above
     * using get_option() and update_option()
     */
  }
}
add_action('wp_footer', 'wpse_63266_update_recently_viewed');
function wpse_63266_show_recently_viewed() {
  $recenty_viewed = get_user_meta(get_current_user_id(), 'recently_viewed', true);
  echo '<pre>';
  print_r($recenty_viewed);
  echo '</pre>';
}
add_action('wpse_63266_recently_viewed', 'wpse_63266_show_recently_viewed');
Cái này đặt trong footer do_action('wpse_63266_recently_viewed');
?>

Last updated