在特定产品 ID woocommerce 上添加自定义字段

时间:2021-07-05 03:09:40

标签: php wordpress 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 语句不起作用。请指教。

1 个答案:

答案 0 :(得分:1)

我已打开调试模式,但在调试日志中出现错误。您必须将 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 存储在变量中的内容。