Получить код купона динамически от WooCommerce в пользовательской функции - PullRequest
2 голосов
/ 15 мая 2019

Со ссылкой на " Разрешить покупку определенных продуктов, только если купон применяется в Woocommerce " Код ответа на один из моих предыдущих вопросов, код купона жестко закодирован вфункции и должны совпадать с существующим кодом купона в Woocommerce.

Но я бы хотел выбрать купон динамически в Woocommerce.

Как динамически получить купон в woocommerce?

Ответы [ 2 ]

1 голос
/ 15 мая 2019

Следующий код расширяет мой предыдущий ответ и добавит флажок в разделе купона WooCommerce>, позволяющий любой код купона быть "обязательным" для определенных определенных элементов:

enter image description here

Таким образом, вам не нужно будет определять код купона в функции.

Весь код:

// Add a custom checkbox to Admin coupon settings pages
add_action( 'woocommerce_coupon_options', 'add_coupon_option_checkbox', 10 );
function add_coupon_option_checkbox() {
    woocommerce_wp_checkbox( array(
        'id'            => 'items_mandatory',
        'label'         => __( 'Force specific items', 'woocommerce' ),
        'description'   => __( 'Make this coupon mandatory for specific items.', 'woocommerce' ),
        'desc_tip'      => false,
    ) );
}

// Save the custom checkbox value from Admin coupon settings pages
add_action( 'woocommerce_coupon_options_save', 'save_coupon_option_checkbox', 10, 2 );
function save_coupon_option_checkbox( $post_id, $coupon ) {
    update_post_meta( $post_id, 'items_mandatory', isset( $_POST['items_mandatory'] ) ? 'yes' : 'no' );
}

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    $targeted_ids    = array(37); // The targeted product ids (in this array)
    $applied_coupons = WC()->cart->get_applied_coupons();
    $coupon_applied  = false;

    if( sizeof($applied_coupons) > 0 ) {
        // Loop through applied coupons
        foreach( $applied_coupons as $coupon_code ) {
            $coupon = new WC_Coupon( $coupon_code );
            if( $coupon->get_meta('items_mandatory') === 'yes' ) {
                $coupon_applied = true;
                break;
            }
        }
    }

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $cart_item ) {
        // Check cart item for defined product Ids and applied coupon
        if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) {
            wc_clear_notices(); // Clear all other notices

            // Avoid checkout displaying an error notice
            wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']->get_name() ), 'error' );
            break; // stop the loop
        }
    }
}

Код помещается в файл functions.php вашей активной дочерней темы (или активной темы). Проверено и работает.

enter image description here

А в кассе:

enter image description here

1 голос
/ 15 мая 2019

Попробуйте, изменения прокомментированы:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    // The targeted product ids (in this array)
    $targeted_ids   = array(37); 
    // Get applied $coupon_names
    $cart_applied_coupons = WC()->cart->get_applied_coupons()
    // Set the variable $coupon_applied to false
    $coupon_applied = false;
    // Create an array to save all coupon names
    $coupon_names = array();
    // Get the available coupons
    $args = array(
        'posts_per_page'   => -1,
        'orderby'          => 'title',
        'order'            => 'asc',
        'post_type'        => 'shop_coupon',
        'post_status'      => 'publish',
    );
    $all_coupons = get_posts( $args );
    if( !empty($all_coupons) ){
      // Loop through the available coupons
      foreach ( $all_coupons as $coupon ) {
          // Get the name for each coupon and add to the previously created array
          $coupon_name = $coupon->post_title;
          array_push( $coupon_names, $coupon_name );
      }
      // If one on the coupons is applied change the value of $coupon_applied to true
      foreach($coupon_names as $coupon_code){
        if( in_array( strtolower($coupon_code), $cart_applied_coupons) ){
          $coupon_applied = true;
          break;
        }
      }
    }


    // Loop through cart items
    foreach(WC()->cart->get_cart() as $cart_item ) {
        // Check cart item for defined product Ids and applied coupon
        if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) {
            wc_clear_notices(); // Clear all other notices

            // Avoid checkout displaying an error notice
            wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']->get_name() ), 'error' );
            break; // stop the loop
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...