且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WooCommerce 产品:仅允许特定用户角色的延期交货

更新时间:2023-11-30 11:46:22

您的代码中存在一些错误和缺失的内容.请改用以下内容:

There are some mistakes and missing things in your code. Use the following instead:

// Custom conditional function targeting specific user roles
function is_allowed_user_role() {
    $targeted_roles = array('administrator', 'shop_manager'); // Here define your targeted user roles
    return (bool) array_intersect( wp_get_current_user()->roles, $targeted_roles );
}

add_filter( 'woocommerce_product_get_stock_status', 'filter_product_stock_status' );
add_filter( 'woocommerce_product_variation_get_stock_status', 'filter_product_stock_status' );
function filter_product_stock_status( $stock_status ) {
    if ( ! is_allowed_user_role() && 'onbackorder' === $stock_status ) {
        $stock_status = 'outofstock';
    }
    return $stock_status;
}

add_filter( 'woocommerce_product_get_backorders', 'filter_product_get_backorders' );
add_filter( 'woocommerce_product_variation_get_backorders', 'filter_product_get_backorders' );
function filter_product_get_backorders( $backorders ){
    return is_allowed_user_role() ? $backorders : 'no';
}

add_filter( 'woocommerce_product_backorders_allowed', 'filter_product_backorders_allowed', 10, 3 );
function filter_product_backorders_allowed( $allowed, $product_id, $product ){
    return is_allowed_user_role() ? $allowed : false;
}

代码位于活动子主题(或活动主题)的functions.php 文件中.经测试有效.

Code goes in functions.php file of the active child theme (or active theme). Tested and works.