WooCommerce:按角色过滤订单

时间:2018-07-17 11:42:56

标签: php wordpress filter woocommerce role

如何按角色过滤订单?我需要按自己的作者(商店经理)过滤它们。

我有这个网址挂钩,它根据添加订单的商店经理显示订单(在此示例中,用户ID为4):

https://mywebsite.com/wp-admin/edit.php?post_type=shop_order&author=4

我有这段代码,不能完全满足我的需要(参考:https://jeroensormani.com/order-woocommerce-orders-per-user-role/):

add_action( 'restrict_manage_posts', 'shop_order_user_role_filter' );
function shop_order_user_role_filter() {
    global $typenow, $wp_query;
    if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) :
        $user_role  = '';
        // Get all user roles
        $user_roles = array();
        foreach ( get_editable_roles() as $key => $values ) :
            $user_roles[ $key ] = $values['name'];
        endforeach;
        // Set a selected user role
        if ( ! empty( $_GET['_user_role'] ) ) {
            $user_role  = sanitize_text_field( $_GET['_user_role'] );
        }
        // Display drop down
        ?><select name='_user_role'>
            <option value=''><?php _e( 'Select a user role', 'woocommerce' ); ?></option><?php
            foreach ( $user_roles as $key => $value ) :
                ?><option <?php selected( $user_role, $key ); ?> value='<?php echo $key; ?>'><?php echo $value; ?></option><?php
            endforeach;
        ?></select><?php
    endif;
}
add_filter( 'pre_get_posts', 'shop_order_user_role_posts_where' );
function shop_order_user_role_posts_where( $query ) {
    if ( ! $query->is_main_query() || ! isset( $_GET['_user_role'] ) ) {
        return;
    }
    $ids    = get_users( array( 'role' => sanitize_text_field( $_GET['_user_role'] ), 'fields' => 'ID' ) );
    $ids    = array_map( 'absint', $ids );
    $query->set( 'meta_query', array(
        array(
            'key' => '_customer_user',
            'compare' => 'IN',
            'value' => $ids,
        )
    ) );
    if ( empty( $ids ) ) {
        $query->set( 'posts_per_page', 0 );
    }
}

0 个答案:

没有答案