I needed to add sortable columns to clients wordpress for custom meta data I created so I used a pre_user_query
hook
add_action('pre_user_query', 'user_column_orderby');
function user_column_orderby($user_search) {
global $wpdb, $current_screen;
if ( 'users' != $current_screen->id )
return;
$vars = $user_search->query_vars;
if('Kön' == $vars['orderby']) {
$user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON {$wpdb->users}.ID=m1.user_id AND (m1.meta_key='gender')";
$user_search->query_orderby = ' ORDER BY UPPER(m1.meta_value) '. $vars['order'];
} elseif ('Ålder' == $vars['orderby']) {
$user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON {$wpdb->users}.ID=m1.user_id AND (m1.meta_key='age')";
$user_search->query_orderby = ' ORDER BY UPPER(m1.meta_value) '. $vars['order'];
} elseif ('Distrikt' == $vars['orderby']) {
$user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON {$wpdb->users}.ID=m1.user_id AND (m1.meta_key='district')";
$user_search->query_orderby = ' ORDER BY UPPER(m1.meta_value) '. $vars['order'];
} elseif ('Kategori' == $vars['orderby']) {
$user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON {$wpdb->users}.ID=m1.user_id AND (m1.meta_key='category')";
$user_search->query_orderby = ' ORDER BY UPPER(m1.meta_value) '. $vars['order'];
}
}
This works fine if you're on the user screen. But I also added a export to csv button, which calls my export-csv.php
file that looks like this:
<?php
$location = $_SERVER['DOCUMENT_ROOT'];
include ($location . '/wp-load.php');
if (current_user_can('manage_options')) {
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="users'.date('YmdHis').'.csv"');
// WP_User_Query arguments
$args = array (
'order' => 'ASC',
'orderby' => 'display_name',
'fields' => 'all',
);
// The User Query
$blogusers = get_users( 'orderby=nicename&order=ASC' );
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
//echo '<span>' . esc_html( $user->user_email ) . '</span>';
print_r($user);
}
}
Now, the problem I'm having is that my .csv
file has a notice:
Notice: Trying to get property of non-object in .../wp-content/themes/mytheme/admin/users_additionals.php on line 133
Which points to the line:
if ( 'users' != $current_screen->id )
in my first code. This happens because I've hooked to the pre_user_query
hook, and I'm querying users in my file. Is there a way to suppress this notice (without going to wp-config.php
and removing the debug code - this is not the solution, just masking the problem)?