You can use the WP_User_Query
class to query on user meta, however, your specific example of querying for a list of users with a join date matching a specific month and from any year requires a query more complex than what you can do out of the box with the WP_User_Query
class.
First, it’s important that the date format be correct and strictly enforced if you’re going to be querying on this data. I’d suggest using a jQuery datepicker widget to enable input of dates into the join date field. YYYY-MM-DD is the standard MySQL date format.
EXAMPLE 1
Here’s an example of a simple query that will load all users who joined this month:
$first = new DateTime();
$first->modify( 'first day of this month' );
$first = $first->format( 'Y-m-d' );
$args = array(
'meta_key' => 'join_date',
'meta_value' => $first,
'meta_compare' => '>=',
);
$user_query = new WP_User_Query( $args );
EXAMPLE 2
Here’s a more complex meta query that will load users between specific dates:
$first = new DateTime();
$first->modify( 'first day of this month' );
$first = $first->format( 'Y-m-d' );
$last = new DateTime();
$last->modify( 'last day of this month' );
$last = $last->format('Y-m-d');
$args = array(
'meta_query' => array(
array(
'key' => 'join_date',
'value' => array( $first, $last ),
'compare' => 'BETWEEN',
'type' => 'DATE'
)
)
);
$user_query = new WP_User_Query( $args );
EXAMPLE 3
For custom queries, you can modify the SQL directly. The first step is to set up a simple query:
$args = array(
'meta_key' => 'join_date',
'meta_value' => 0,
);
$user_query = new WP_User_Query( $args );
$users = $user_query->get_results();
foreach( $users as $user ):
echo $user->user_nicename;
echo ' joined ';
echo get_user_meta( $user->ID, 'join_date', true );
endforeach;
Next, we add an action to pre_user_query
to check for our simple query, and modify the SQL to just match the month and ignore year:
function wpse52318_user_query( $query ){
if( $query->query_vars['meta_key'] == 'join_date' && $query->query_vars['meta_value'] === 0 ):
global $wpdb;
$thismonth = date('m');
$query->query_where = "WHERE 1=1 AND ( $wpdb->usermeta.meta_key = 'join_date' AND ( MONTH( $wpdb->usermeta.meta_value ) = $thismonth ) )";
endif;
return $query;
}
add_action( 'pre_user_query', 'wpse52318_user_query' );