source

woocommerce의 특정 제품에 대한 카트 품목 수량 변경

nicesource 2023. 2. 23. 22:55
반응형

woocommerce의 특정 제품에 대한 카트 품목 수량 변경

특정 제품에서 WooCommerce 수량을 변경할 수 있습니까?

시도했습니다.

global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    foreach($items as $item => $values) { 
        $_product = $values['data']->post; 
        echo "<b>".$_product->post_title.'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
        $price = get_post_meta($values['product_id'] , '_price', true);
        echo "  Price: ".$price."<br>";
    } 

카트에서 특정 제품 ID를 가져오려면 어떻게 해야 합니까?

수량을 변경하려면 해당 코드 뒤를 참조하십시오.다시 방문한 코드:

foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { 
    $product = $cart_item['data']; // Get an instance of the WC_Product object
    echo "<b>".$product->get_title().'</b>  <br> Quantity: '.$cart_item['quantity'].'<br>'; 
    echo "  Price: ".$product->get_price()."<br>";
} 

갱신일 :특정 제품의 수량을 변경하려면 이 커스텀 기능을 사용해야 합니다.woocommerce_before_calculate_totals액션 훅:

add_action('woocommerce_before_calculate_totals', 'change_cart_item_quantities', 20, 1 );
function change_cart_item_quantities ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE below define your specific products IDs
    $specific_ids = array(37, 51);
    $new_qty = 1; // New quantity

    // Checking cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product_id = $cart_item['data']->get_id();
        // Check for specific product IDs and change quantity
        if( in_array( $product_id, $specific_ids ) && $cart_item['quantity'] != $new_qty ){
            $cart->set_quantity( $cart_item_key, $new_qty ); // Change quantity
        }
    }
}

코드가 기능합니다.php 파일(또는 활성 테마)입니다(또는 활성 테마)을 입력합니다.

테스트 완료 및 동작

언급URL : https://stackoverflow.com/questions/48897882/change-the-cart-item-quantity-for-specific-products-in-woocommerce

반응형