您可以使用WP_User_Query
类来查询用户元,但是,查询加入日期与特定月份和任何年份匹配的用户列表的特定示例需要比使用WP_User_Query
班
首先,如果要查询此数据,则必须正确并严格执行日期格式。我建议使用jQuery datepicker小部件将日期输入到join date字段中。YYYY-MM-DD是标准的MySQL日期格式。
下面是一个简单查询的示例,它将加载本月加入的所有用户:
$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 );
示例2有一个更复杂的元查询,它将在特定日期之间加载用户:
$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 );
示例3对于自定义查询,可以直接修改SQL。第一步是设置一个简单的查询:
$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;
接下来,我们向
pre_user_query
要检查我们的简单查询,并修改SQL以仅匹配月份而忽略年份,请执行以下操作:
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\' );