Add a product tab to Woocommerce with a checkbox to add functionality to add a second "Add to Cart".
P粉262113569
2023-07-31 15:01:29
<p>I could use some help from you, thank you very much for your efforts! </p><p>My problem is that the installed plugin replaces the standard add to cart button on the product page. I don't want to change it and I need to add a second add to cart button below it. The problem is, another plugin for free product samples requires a regular add to cart button. </p><p>When I add the global script it works on all products. </p><p><br /></p>
<pre class="brush:php;toolbar:false;">Add_action( 'woocommerce_product_meta_start', 'woocommerce_template_single_add_to_cart, 1 );</pre>
<p>I would like this feature added to the product tab and can be enabled or disabled on selected products via a checkbox. </p><p>So far, my code has done nothing. The checkboxes work and the checkboxes save fine. But the code snippet does not execute the add to cart command on the product frontend page. </p><p><br /></p>
<pre class="brush:php;toolbar:false;">// Add checkbox field to the Product tab in the admin area
function add_checkbox_to_product_tab() {
// Add checkbox field to the General tab
woocommerce_wp_checkbox( array(
'id' => 'add_to_cart_checkbox',
'label' => 'Warenkorb Hinzufügen',
'desc_tip' => false, // true or false, show description directly or as tooltip
'description' => 'ja'
) );
}
add_action( 'woocommerce_product_options_general_product_data', 'add_checkbox_to_product_tab' );
// Save checkbox field value
function save_checkbox_value( $product ) {
$checkbox = isset( $_POST['add_to_cart_checkbox'] ) ? 'yes' : 'no';
$product->update_meta_data( 'add_to_cart_checkbox', $checkbox );
}
add_action( 'woocommerce_admin_process_product_object', 'save_checkbox_value' );
// Add action when checkbox is selected with 'yes'
function add_action_when_checkbox_selected( $product_id ) {
$checkbox_value = get_post_meta( $product_id, '_add_to_cart_checkbox', true );
if ( $checkbox_value == 'yes' ) {
do_action( 'woocommerce_product_meta_start' );
do_action( 'woocommerce_template_single_add_to_cart' );
}
}
add_action( 'woocommerce_template_single_add_to_cart', 'add_action_when_checkbox_selected', 1 );</pre>
<p><br /></p>
You can use the `woocommerce_product_meta_start` hook. Please see the code below.
After testing, the code is valid.