В вашем коде есть ошибки и ошибки ... Поскольку $valueArray
не определено в вашем коде, первый цикл foreach не имеет никакого эффекта, и код становится активным после него.Для таргетинга на категории товаров в корзине вы можете использовать условную функцию WordPress has_term()
.
Вместо этого попробуйте следующее (для Woocommerce 3 +) :
// Updating cart item prices conditionally
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 100, 1 );
function custom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Your product categories to avoid
$categories = array("shirts", "games");
foreach ( $cart->get_cart() as $cart_item ) {
if( isset($cart_item['wccpf_cost']['user_val']) && ! has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$cart_item['data']->set_price($cart_item['wccpf_cost']['user_val']);
}
}
}
Кодидет в файл function.php вашей активной дочерней темы (или активной темы).Это должно работать.
Но если вы хотите настроить таргетинг на родительские категории продуктов, вам нужно будет использовать в своем коде пользовательскую условную функцию has_product_categories()
вместо:
// Custom conditional function that checks for parent product categories
function has_product_categories( $product_id, $categories ) {
// Initializing
$parent_term_ids = $categories_ids = array();
$taxonomy = 'product_cat';
// Convert categories term names and slugs to categories term ids
foreach ( $categories as $category ){
if( is_numeric( $category ) ) {
$categories_ids[] = (int) $category;
} elseif ( term_exists( sanitize_title( $category ), $taxonomy ) ) {
$categories_ids[] = get_term_by( 'slug', sanitize_title( $category ), $taxonomy )->term_id;
}
}
// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
if( $term->parent > 0 ){
$parent_term_ids[] = $term->parent; // Set the parent product category
$parent_term_ids[] = $term->term_id; // (and the child)
} else {
$parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
}
}
return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}
// Updating cart item prices conditionally
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 100, 1 );
function custom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Your product categories to avoid
$categories = array("shirts", "games");
foreach ( $cart->get_cart() as $cart_item ) {
if( isset($cart_item['wccpf_cost']['user_val']) && ! has_product_categories( $cart_item['product_id'], $categories ) ) {
$cart_item['data']->set_price($cart_item['wccpf_cost']['user_val']);
}
}
}
Код входит в кодФайл function.php вашей активной дочерней темы (или активной темы).Это должно работать.
Связанные темы: