In WooCommerce, I have added a checkbox in single product pages and also on the products loops, where the user can check that they want to request a certificate.
My code below works fine on single product pages. However, in the products loops, the value of the check box is always taken, even if the checkbox is unchecked. It should only be taken if the checkbox is checked.
Here is my code:
function add_name_on_certificate_field() {
echo '<table class="certificate" cellspacing="0">
<tbody>
<tr>
<td class="value">
Certificate: <input type="checkbox" name="name_on_certificate" value="certificate" "/>
</td>
</tr>
</tbody>
</table>';}
add_action( 'woocommerce_before_add_to_cart_button', 'add_name_on_certificate_field');
function save_name_on_certificate_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['name_on_certificate'] ) ) {
$cart_item_data[ 'name_on_certificate' ] = $_REQUEST['name_on_certificate'];
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_name_on_certificate_field', 10, 2 ); code here
function render_meta_on_cart_and_checkout2( $cart_data, $cart_item = null ) {
$custom_items = array();
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['name_on_certificate'] ) ) {
$custom_items[] = array( "name" => 'Certificate', "value" =>
$cart_item['name_on_certificate']);
}
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout2', 10, 2 );
function certificate_order_meta_handler( $item_id, $values, $cart_item_key ) {
if( isset( $values['name_on_certificate'] ) ) {
wc_add_order_item_meta( $item_id, "name_on_certificate", $values['name_on_certificate']);
}
}
add_action( 'woocommerce_add_order_item_meta', 'certificate_order_meta_handler', 1, 3 );
function add_custom_fields_on_product_listing2() {
global $product;
echo '</a><div class="sark-custom-fields-wrapper">
<input type="checkbox" id="name_on_certificate-'. $product->id .'" value="certificate-required" /> </div>';
}
add_action( "woocommerce_after_shop_loop_item", 'add_custom_fields_on_product_listing2', 1 );
function inject_custom_field_script2() { ?>
<script type="text/javascript">
jQuery(document).on("adding_to_cart", function( e, btn, data ){
data["name_on_certificate"] = jQuery("#name_on_certificate-" + btn.attr( "data-product_id" )).val();
return true;
});
</script>
<?php }
add_action( "woocommerce_after_main_content", 'inject_custom_field_script2', 1 );
For info, there is already a text field, where you can set the size of the product that works fine.
Any help will be appreciated.