简体   繁体   中英

Using ACF true/false field on WooCommerce single product page

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?

While acf/init is similar to the WordPress init action, I wouldn't use it.

Init hooks are performed constantly.. since you want to apply an action on the single product page it's best to use a hook that only applies to that page, and will only run on those kinds of pages.

For example you can use the woocommerce_single_product_summary hook. It might also be useful to test fields by hard coding before retrieving them.


So you get:

function action_woocommerce_single_product_summary() {
    // Get field
    //$move_cart = get_field( 'move_cart' );
    
    // Set true OR false
    $move_cart = false;

    // When true
    if ( $move_cart ) {
        add_action( 'woocommerce_after_single_product', 'my_callback_function', 9 );
    } else {
        add_action( 'woocommerce_before_add_to_cart_form', 'my_callback_function', 9 );
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 1 );

function my_callback_function() {
    echo '<p style="color: red; font-size: 20px;">Hello World!</p>';
}

If the above step works, you can replace the hard coded field with the desired code/field

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM