使用用户元数据过滤WooCommerce订单查询

时间:2019-05-12 作者:landorid

我想列出我的Woocommerce商店的订单。我有我的用户元。(取消订阅)我只想在订单的用户取消订阅==0时列出该订单。

我向客户提供了工作代码:

$args = array(
    \'role\'       => \'customer\',
    \'number\'     => - 1,
    \'meta_query\' => [
        \'relation\' => \'OR\',
        [
            \'key\'     => \'unsubscribed\',
            \'compare\' => \'!=\',
            \'value\'   => 1
        ],
        [
            \'key\'     => \'unsubscribed\',
            \'value\'   => 0,
            \'compare\' => \'NOT EXISTS\'
        ]
    ],
);

$query  = new WP_User_Query( $args );
我想做类似的查询wc_get_orders 但它不起作用:

$args   = [
    \'limit\' => - 1,
    \'meta_query\' => [
        \'relation\' => \'OR\',
        [
            \'key\'     => \'unsubscribed\',
            \'compare\' => \'!=\',
            \'value\'   => 1
        ],
        [
            \'key\'     => \'unsubscribed\',
            \'value\'   => 0,
            \'compare\' => \'NOT EXISTS\'
        ]
    ]
];

$orders = wc_get_orders( $args );

1 个回复
最合适的回答,由SO网友:LoicTheAztec 整理而成

我看到了两种可能的方法:

1) 使用WP_User_Query 在a中WC_Order_Query 使用customer_id 参数如下:

// Users query
$user_ids = (array) get_users([
    \'role\'       => \'customer\',
    \'number\'     => - 1,
    \'fields\'     => \'ID\',
    \'meta_query\' => [
        \'relation\' => \'OR\',
        [
            \'key\'     => \'unsubscribed\',
            \'compare\' => \'!=\',
            \'value\'   => 1
        ],
        [
            \'key\'     => \'unsubscribed\',
            \'compare\' => \'NOT EXISTS\'
        ]
    ],
]);

// Orders query (using the users IDs from the user query)
$orders = wc_get_orders([
    \'limit\'       => - 1,
    \'status\'      => [\'on-hold\',\'processing\',\'completed\'],
    \'customer_id\' => $user_ids,
]);

// Loop through Order IDs
foreach( $orders as $order ) {
    // Get the Order ID
    $order_id = $order->get_id();

    // And so on …
}
2)或者您可以将唯一的打火机SQL查询用于WPDB 类,如:

$global $wpdb;

$order_ids = $wpdb->get_col( "
    SELECT DISTINCT ID
    FROM {$wpdb->prefix}posts o
    INNER JOIN {$wpdb->prefix}postmeta om
        ON o.ID = om.post_id
    INNER JOIN {$wpdb->prefix}usermeta um
        ON om.meta_value = um.user_id
    INNER JOIN {$wpdb->prefix}usermeta um2
        ON um.user_id = um2.user_id
    WHERE o.post_type = \'shop_order\'
    AND o.post_status IN (\'wc-on-hold\',\'wc-processing\',\'wc-completed\')
    AND om.meta_key = \'_customer_user\'
    AND um.meta_key = \'wp_capabilities\'
    AND um.meta_value LIKE \'%customer%\'
    AND um2.meta_key = \'unsubscribed\'
    AND ( um2.meta_value = \'0\' OR um2.meta_value = NULL )
");

// Loop through Order IDs
foreach( $order_ids as $order_id ) {
    // Get an instance of the WC_Order Object
    $order = wc_get_order($order_id);

    // And so on …
}

相关推荐