Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a profile (a CPT) directory set up and I'm trying to find a way to sort the results based on the last login time of the post author. The goal is to reward recently logged in authors by pushing their profiles to the top of the query results, thereby increasing the visibility of their profiles.

I know how to query using custom fields but I'm not sure how to go about querying using usermeta.

The functions I have set up are:

// Catch the time they login and save it
function set_last_login($login) {
  $user = get_userdatabylogin($login);
  update_usermeta( $user->ID, 'last_login', current_time('mysql') );
}
add_action('wp_login', 'set_last_login');

// Display the time
function get_last_login($user_id) {
  $last_login = get_user_meta($user_id, 'last_login', true);
  $date_format = get_option('date_format') . ' ' . get_option('time_format');
  $the_last_login = mysql2date($date_format, $last_login, false);
  return $the_last_login;
}

// Show friendly last login
function lastseen() {
    $lastseen = get_last_login(get_the_author_meta('ID'));
    $last_login_unix = strtotime( $lastseen );
    echo human_time_diff( $last_login_unix );
} 

The query on my page is:

   $temp = $wp_query;
   $wp_query= null;
   $wp_query = new WP_Query();
   $wp_query->query('post_type=teacher'.'&paged='.$paged);

How can I add sorting on usermeta (e.g. last login) to this query?

share|improve this question
add comment

1 Answer

You have to add meta_key, orderby and order parameters to your query as described in the Codex: Order & Orderby Parameters:

<?php
$args = array(
    'post_type' => 'teacher',
    'paged' => $paged,
    'meta_key' => 'last_login',
    'orderby' => 'meta_value',
    'order' => 'DESC'
);
$my_custom_query = new WP_Query($args);

Also note I don't use $wp_query variable to store the query. See WP_Query Usage for example and description why.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.