将基于 ACF 字段的自定义 "Add to cart" 按钮添加到 WooCommerce 单品页面
Add custom "Add to cart" button based on ACF field to WooCommerce single product page
我想使用此代码有条件地在单个产品页面上添加额外的自定义“添加到购物车按钮”:
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';
}
}
此变量是来自 ACF 的字段 $mamut = get_field('mamut');
然而,当我将这段代码放入我的 functions.php
文件时,单个产品页面崩溃了
我正在使用主题 Twenty19 和 Elementor Pro。
我试过删除操作然后添加不同的操作,但它不起作用。我还尝试制作简码并使用 Elementor 输入它们,但随后简码显示为文本。
- 您使用
$product->get_id();
而 $product
未定义
- 您可以使用
$product->get_stock_status();
而不是 get_post_meta( get_the_ID(), '_stock_status', true );
所以你得到
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 );
我想使用此代码有条件地在单个产品页面上添加额外的自定义“添加到购物车按钮”:
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';
}
}
此变量是来自 ACF 的字段 $mamut = get_field('mamut');
然而,当我将这段代码放入我的 functions.php
文件时,单个产品页面崩溃了
我正在使用主题 Twenty19 和 Elementor Pro。
我试过删除操作然后添加不同的操作,但它不起作用。我还尝试制作简码并使用 Elementor 输入它们,但随后简码显示为文本。
- 您使用
$product->get_id();
而$product
未定义 - 您可以使用
$product->get_stock_status();
而不是get_post_meta( get_the_ID(), '_stock_status', true );
所以你得到
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 );