简体   繁体   中英

Add custom "Add to cart" button based on ACF field to WooCommerce single product page

I want to add an additionall custom "Add to cart button" on the single product page conditionally using this code:

add_action( 'woocommerce_product_meta_end' , 'add_to_cart_custom', 10 ); 

function add_to_cart_custom() {

    $mamut = get_field('mamut');
    $stockstatus = get_post_meta( get_the_ID(), '_stock_status', true );
    $id = $product->get_id();
    

    if ($mamut) {
    echo 'Send request';
    
}elseif(!$mamut and $stockstatus === 'outofstock'){

        echo  'Send request - Mamut';

}elseif(!$mamut and $stockstatus === "instock" ) {
        
        echo 'Add to cart';

   }
}

This variable is field from ACF $mamut = get_field('mamut');

However when I put this code into my functions.php file, the single product page crash

I am using theme Twenty nineteen and Elementor Pro.

I've tried to remove actions and then add different one but it doesn't work. Also I tried to make shortcodes and enter them using Elementor , but then shortcodes displayed as text.

  • Your using $product->get_id(); while $product is not defined
  • You could use $product->get_stock_status(); instead of get_post_meta( get_the_ID(), '_stock_status', true );

So you get

function add_to_cart_custom() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get field - function from ACF plugin, plugin must be actived for this
        $mamut = get_field( 'mamut' );
        
        // Get stock status
        $stock_status = $product->get_stock_status();
        
        // If value exists
        if ( $mamut ) {
            echo 'Send request';
        } elseif( ! $mamut && $stock_status === 'outofstock' ) {
            echo 'Send request - Mamut';
        } elseif( ! $mamut && $stock_status === 'instock' ) {
            echo 'Add to cart';
        }
    }
}
add_action( 'woocommerce_product_meta_end' , 'add_to_cart_custom', 10, 0 ); 

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