Yuri
Yuri

Reputation: 2248

Add a specific word next to quantity input field for specific products on WooCommerce cart page

I have two products - 'counseling' and 'testing', and I want to display a specific word ('sessions' and 'testings') next to (or under) the quantity input field for each of them on the shopping cart page, but I can't find a hook for this. How this can be achieved?

Right now I display a generic word ('items') for both products, but this is not what I want.

/** Display a custom text next to the quantity input field **/
add_action( 'woocommerce_after_quantity_input_field', function() {
    if( is_cart() ) {
        echo '<p class="additional-text">(items)</p>';
    }
} );

enter image description here

Upvotes: 2

Views: 1396

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29624

You are using the wrong hook. For the cart page you can use:

function filter_woocommerce_cart_item_quantity( $product_quantity, $cart_item_key, $cart_item ) {
    // Append to
    $product_quantity .= '<p class="additional-text">(items)</p>';
        
    return $product_quantity;
}
add_filter( 'woocommerce_cart_item_quantity', 'filter_woocommerce_cart_item_quantity', 10, 3 );

To apply this only to certain products, use

function filter_woocommerce_cart_item_quantity( $product_quantity, $cart_item_key, $cart_item ) {
    // The targeted product ids
    $targeted_ids = array( 30, 200 );

    // Computes the intersection of arrays
    if ( array_intersect( $targeted_ids, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
        $product_quantity .= '<p class="additional-text">(items)</p>';
    }
    
    return $product_quantity;
}
add_filter( 'woocommerce_cart_item_quantity', 'filter_woocommerce_cart_item_quantity', 10, 3 );

OR

function filter_woocommerce_cart_item_quantity( $product_quantity, $cart_item_key, $cart_item ) {
    // Checks if a value exists in an array
    // Product ID 30
    if ( in_array( 30, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
        $product_quantity .= '<p class="additional-text">(items)</p>';
    // Product ID 817
    } elseif ( in_array( 817, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
        $product_quantity .= '<p class="additional-text">(other text)</p>';     
    }
    
    return $product_quantity;
}
add_filter( 'woocommerce_cart_item_quantity', 'filter_woocommerce_cart_item_quantity', 10, 3 );

Upvotes: 3

Related Questions