John Davidson

php - Using ACF true/false field on WooCommerce single product page

0 comments
Message:


I have a WooCommerce site and in the single product page I have a custom checkbox to agree to terms before the add to cart button, but I am trying to add a true/false field in the dashboard so that this checkbox can be moved to a different position on the page.


My functions look like this:


add_action( 'acf/init', "acf_move_checkbox", 10 );

function acf_move_checkbox() {

$move_cart = get_field('move_cart');

if ($move_cart) {

add_action( 'woocommerce_after_single_product', "acf_product_terms", 10 );

} else {

add_action( 'woocommerce_before_add_to_cart_form', "acf_product_terms", 10 );

}

// More code

}

And nothing is happening, am I along the right lines with this or way off?



My Answer:
function my_acf_init() {
// Check if ACF is active
if( function_exists('acf_add_local_field_group') ) {
// Add a new field group
acf_add_local_field_group(array(
'key' => 'group_1',
'title' => 'Product Settings',
'fields' => array(
array(
'key' => 'field_1',
'label' => 'Move Checkbox',
'name' => 'move_checkbox',
'type' => 'true_false',
'instructions' => 'Check this box to move the checkbox to a different position on the page',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => '',
),
'default_value' => 0,
'ui' => 1,
'ui_on_text' => '',
'ui_off_text' => '',
),
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'product',
),
),
),
));
}
}
add_action('acf/init', 'my_acf_init');

// Function to move checkbox based on ACF field value
function move_checkbox_on_product_page() {
$move_checkbox = get_field('move_checkbox');
if($move_checkbox) {
// Move checkbox to a different position on the page
}
}
add_action('woocommerce_before_add_to_cart_button', 'move_checkbox_on_product_page');

In this code snippet, we first add a new field group using ACF with a true/false field called 'move_checkbox' in the product settings. We then check the value of this field in the 'move_checkbox_on_product_page' function and move the checkbox to a different position on the page if the field is checked.

Make sure to replace 'group_1' with a unique key for your field group and adjust the location and conditional logic as needed.

Rate this post

4 of 5 based on 1254 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us