I am currently working on a WordPress website, with WooCommerce functionality.

I have created a Custom Text Box, which appears on the Product Page, which allows shoppers to enter their own Custom Text which they would like to have applied to the associated Product. Each Letter is assigned a price and is added to the overall Product Price.

Initially, each letter was priced at the same on every product. However, the client has introduced Products which consist of a more luxuries material when placing letters on the product. These ‘luxurious letters’ are more expensive.

Consequently, I now need to place the initial coding inside Conditional Tags, so that if the shopper lands on the ‘luxurious item’, they are charged an increased price per letter.

I have attempted to achieve this goal by inserting the below code into the functions.php file. The code works without the Conditional Tags, so I can only assume I am doing something wrong. I have commented the Conditional Tags, so it is seen where the possible error could lie:

<?php 
    function calculate_custom_text_price( $cart_object ) {  
        if (is_single('product-slug-url')) { //Additional Conditional Tag            
            foreach ( $cart_object->cart_contents as $key => $value ) {
                if( isset( $value["engrave_text"] ) ) {
                $chars = strlen( $value["engrave_text"] );
                $engrave_text_fee = $chars * 2;
                $orgPrice = floatval( $value['data']->price );
                $value['data']->set_price( $orgPrice + $engrave_text_fee );
                }
            }
        }
        if (is_single('product-slug-url')) {  //Additional Conditional Tag            
            foreach ( $cart_object->cart_contents as $key => $value ) {
                if( isset( $value["engrave_text"] ) ) {
                $chars = strlen( $value["engrave_text"] );
                $engrave_text_fee = $chars * 5;
                $orgPrice = floatval( $value['data']->price );
                $value['data']->set_price( $orgPrice + $engrave_text_fee );
                }
            }
        }
    }
add_action( 'woocommerce_before_calculate_totals', 'calculate_custom_text_price', 99 );
?>

Any help on this matter, would be greatly appreciated.

Read more here: How do I place a function inside Conditional Tags, within the `functions.php` file?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: