I am currently working on a WordPress website, with WooCommerce functionality.
Each Product Page, has a Custom Field which allows site visitors to enter text that they would like to apply to the Product. Charges are applied on a 'per letter entered' basis.
To work out the overall cost of the product (Product Price + Custom Letters Entered), I have inserted the following code, into the functions.php
file:
<?php
function calculate_engrave_text_fee( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["engrave_text"] ) ) {
// Quantity of characters entered into Custom Text Field:
$chars = strlen( $value["engrave_text"] );
// Characters Entered Multiplied by Cost of Each Letter:
$engrave_text_fee = $chars * 3; //Need to dynamically call this.
$orgPrice = floatval( $value['data']->price );
$value['data']->set_price( $orgPrice + $engrave_text_fee );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_engrave_text_fee', 99 );
?>
The above code works absolutely fine; with one exception.
Since the cost of each Letter will be different, depending on the product, having a static entry such as $engrave_text_fee = $chars * 3;
is not ideal. Alternatively, I have created a Custom Field in the WooCommerce Product Dashboard whereby a Site Admin is able to enter the price for each Product's individual Custom Lettering.
The Problem
To dynamically call the Custom Field entry, from the WooCommerce Product Dashboard and place this into the Maths above, I tried replacing: $engrave_text_fee = $chars * 3;
with:
$engrave_text_fee = $chars * <?php global $post; echo get_post_meta($post->ID,'_pricing_engrave_text_option',true)?>;
Unfortunately, this only sends the website offline. I can only assume there is an issue with the coding syntax!? Is anyone able to point out where I may be going wrong here?