[英]add a custom field on a specific product IDs woocommerce
我想在functions.php中的特定集合woocommerce產品上添加一個自定義字段“產品描述”。 見下面的代碼:
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
顯存儲在變量中的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.