你可以换个思路来解决问题。除了只为特定用户显示私有产品您可以为所有其他用户角色隐藏它们 (让产品保持“发布”状态)。
这样就不会出现Ajax问题了。
如果用户具有以下函数的$user_roles数组中定义的角色之一,它将隐藏$product_ids_to_hide数组中的所有产品:
// hide products based on user role
add_filter( 'woocommerce_product_is_visible', 'hide_products_by_user_role', 10, 2 );
function hide_products_by_user_role( $visible, $product_id ) {
// only if the user is logged in
if ( ! is_user_logged_in() ) {
return $visible;
}
// set the product ids to hide
$product_ids_to_hide = array( 12, 14 );
// sets the user roles for which products are to be hidden
$user_roles = array( 'custom_role_1', 'custom_role_2' );
$user = wp_get_current_user();
if ( array_intersect( $user_roles, $user->roles ) && in_array( $product_id, $product_ids_to_hide ) ) {
return false;
}
return $visible;
}
回复您的评论:
如果您希望允许用户根据用户角色修改要隐藏的产品 ID,您可以创建一个 .csv 文件以上传到 FTP,其中包含产品 ID 列表,每行一个强>.
如果您的客户将来想要删除或添加产品 ID,他可以简单地使用 FTP 导入覆盖 .csv 文件或直接在文件管理器中(如果托管允许)。
我作为示例创建的文件名为product-ids-to-hide.csv,需要上传到与functions.php 文件相同的目录。 不需要标题。这是一个示例:
349
235
456
745
这将是新的更新功能:
// hide products based on user role
add_filter( 'woocommerce_product_is_visible', 'hide_products_by_user_role', 10, 2 );
function hide_products_by_user_role( $visible, $product_id ) {
// only if the user is logged in
if ( ! is_user_logged_in() ) {
return $visible;
}
// sets the user roles for which products are to be hidden
$user_roles = array( 'custom_role_1', 'custom_role_2' );
$user = wp_get_current_user();
// only if the user has at least one role present in the array
if ( empty( array_intersect( $user_roles, $user->roles ) ) ) {
return $visible;
}
// get an array with product ids
$product_ids_to_hide = file( realpath( __DIR__ . '/product-ids-to-hide.csv' ), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
if ( in_array( $product_id, $product_ids_to_hide ) ) {
return false;
}
return $visible;
}
代码已经过测试并且可以运行。将其添加到您的活动主题的 functions.php 中。