在特定的产品ID上添加一个自定义字段wooccommerce



我想添加一个自定义字段"产品描述";关于一个特定的集合wooccommerce产品在functions.php。参见下面的代码:

add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');
function wdm_add_custom_fields( $cart ) {
global $product;
ob_start();
?>
<div class="wdm-custom-fields">
<label>Product Description</label>: <input type="text" name="wdm_name">
</div>
<div class="clear"></div>
<?php
$content = ob_get_contents();
$targeted_ids = array(29, 27, 28, 72, 84, 95);
ob_end_flush();

foreach ( $cart->get_cart() as $item ) {
if ( array_intersect($targeted_ids, array($item['product_id'], $item['variation_id']) ) );
}
return $content;
}

我不知道Wordpress给出的代码出了什么问题;此网站出现严重错误"注意我在wp-config.php文件中打开了WordPress错误报告,但它没有显示任何错误。

define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', true);

也许if语句不起作用。请告知。

我打开了调试模式,在调试日志中出现错误。您必须将define( 'WP_DEBUG_LOG', true );添加到wp-config.php文件中,才能将错误记录到名为debug.log 的文件中

不要在foreach中使用$cart,而是使用WC()->cart->get_cart()

但是,如果您的要求是在单个产品页面中显示特定产品ID的自定义字段,那么您可以使用以下内容。

add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');
function wdm_add_custom_fields() {
global $product;
$targeted_ids = array(29, 27, 28, 72, 84, 95);
if(in_array( $product->get_id(), $targeted_ids ) ){
?>
<div class="wdm-custom-fields">
<label>Product Description</label>: <input type="text" name="wdm_name">
</div>
<div class="clear"></div>
<?php
}
}

假设您需要根据产品ID在单个产品页面上显示自定义字段,您就错了。您试图从购物车中获取产品,这意味着,应该将产品添加到购物车中,以便显示自定义字段。相反,您应该从global $product变量访问产品ID。

此外,您不需要将数据返回到操作挂钩,您可以编写html或仅echo存储在变量中的内容。

相关内容

最新更新