3

I have created a new column in the user table list (admin page) and would like the column to be searchable in the search query, How do i add the meta to the search users query ?

/**
 * Create user column (admin panel)
 */
add_filter( 'manage_users_columns', 'new_modify_user_table' );
function new_modify_user_table( $column ) 
{
    $column['kundnummer'] = 'Kundnummer';
    return $column;
}

/**
 * Add content to user column (admin panel)
 */
add_filter( 'manage_users_custom_column', 'new_modify_user_table_row', 10, 3 );
function new_modify_user_table_row( $val, $column_name, $user_id ) 
{
    switch ($column_name) {
        case 'kundnummer' :
            return get_user_meta( $user_id, 'woocommerce_customer_id', true );
            break;
        default:
    }
    return $val;
}

enter image description here

Solution

/**
 * Searching Meta Data in Admin
 */
add_action('pre_user_query','yoursite_pre_user_search');
function yoursite_pre_user_search($user_search) {
    global $wpdb;
    if (!isset($_GET['s'])) return;

    //Enter Your Meta Fields To Query
    $search_array = array("customer_id", "woocommerce_customer_id", "first_name", "last_name");

    $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID={$wpdb->usermeta}.user_id AND (";
    for($i=0;$i<count($search_array);$i++) {
        if ($i > 0) $user_search->query_from .= " OR ";
            $user_search->query_from .= "{$wpdb->usermeta}.meta_key='" . $search_array[$i] . "'";
        }
    $user_search->query_from .= ")";        
    $custom_where = $wpdb->prepare("{$wpdb->usermeta}.meta_value LIKE '%s'", "%" . $_GET['s'] . "%");
    $user_search->query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$custom_where} OR ",$user_search->query_where);

}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.