Custom Product Configurator
add_filter( ‘woocommerce_add_cart_item_data’, ‘add_custom_data_to_cart’, 10, 2 );
function add_custom_data_to_cart( $cart_item_data, $product_id ) {
// Preluăm datele din $_POST
if ( isset( $_POST[‘custom_width’] ) ) {
$cart_item_data[‘custom_width’] = sanitize_text_field( $_POST[‘custom_width’] );
$cart_item_data[‘custom_height’] = sanitize_text_field( $_POST[‘custom_height’] );
$cart_item_data[‘custom_material’] = sanitize_text_field( $_POST[‘custom_material’] );
$cart_item_data[‘custom_color’] = sanitize_text_field( $_POST[‘custom_color’] );
$cart_item_data[‘custom_extras’] = sanitize_text_field( $_POST[‘custom_extras’] );
$cart_item_data[‘custom_price’] = sanitize_text_field( $_POST[‘custom_price’] );
// Generăm un identificator unic pentru produs
$cart_item_data[‘unique_key’] = md5( microtime() . rand() );
}
return $cart_item_data;
}
add_filter( ‘woocommerce_get_item_data’, ‘display_custom_data_in_cart’, 10, 2 );
function display_custom_data_in_cart( $item_data, $cart_item ) {
if ( isset( $cart_item[‘custom_width’] ) ) {
$item_data[] = array(
‘name’ => ‘Width’,
‘value’ => $cart_item[‘custom_width’] . ‘ mm’,
);
$item_data[] = array(
‘name’ => ‘Height’,
‘value’ => $cart_item[‘custom_height’] . ‘ mm’,
);
$item_data[] = array(
‘name’ => ‘Material’,
‘value’ => $cart_item[‘custom_material’],
);
$item_data[] = array(
‘name’ => ‘Color’,
‘value’ => $cart_item[‘custom_color’],
);
$item_data[] = array(
‘name’ => ‘Extras’,
‘value’ => $cart_item[‘custom_extras’],
);
}
return $item_data;
}
add_action( ‘woocommerce_before_calculate_totals’, ‘add_custom_price’, 10, 1 );
function add_custom_price( $cart ) {
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) ) {
return;
}
foreach ( $cart->get_cart() as $cart_item ) {
if ( isset( $cart_item[‘custom_price’] ) ) {
$cart_item[‘data’]->set_price( $cart_item[‘custom_price’] );
}
}
}
add_filter( ‘woocommerce_add_to_cart_validation’, ‘validate_custom_data’, 10, 3 );
function validate_custom_data( $passed, $product_id, $quantity ) {
if ( empty( $_POST[‘custom_width’] ) || empty( $_POST[‘custom_height’] ) ) {
wc_add_notice( ‘Please provide valid dimensions.’, ‘error’ );
return false;
}
return $passed;
}