【问题标题】:Set a default value to a checkout field based on product ID in WooCommerce cart根据 WooCommerce 购物车中的产品 ID 为结帐字段设置默认值
【发布时间】:2022-01-26 01:43:39
【问题描述】:

我隐藏了billing_email 字段,并为此字段设置了一个默认值,即特定的电子邮件地址。

我在functions.php中插入的代码如下:

add_filter( 'woocommerce_checkout_fields' , 'default_values_checkout_fields' );
  function default_values_checkout_fields( $fields ) {
    // You can use this for postcode, address, company, first name, last name and such. 
    $fields['billing']['billing_email']['placeholder'] = 'mymail@hotmail.hr';
    $fields['billing']['billing_email']['autocomplete'] = 'mymail@hotmail.fr';
    $fields['billing']['billing_email']['default'] = 'mymail@hotmail.fr';
    return $fields;
}

我实际上希望根据所购买的产品将不同的电子邮件设置为默认电子邮件。 (已经购物车只允许一种产品)。

这些值可以用如下sn-p如下所示的条件设置吗?

add_filter( 'woocommerce_checkout_fields' , 'default_values_checkout_fields' );
function default_values_checkout_fields( $fields ) {
    // You can use this for postcode, address, company, first name, last name and such. 

    if $product_id === 17 {
        $fields['billing']['billing_email']['placeholder'] = 'mymail@hotmail.hr';
        $fields['billing']['billing_email']['autocomplete'] = 'mymail@hotmail.fr';
        $fields['billing']['billing_email']['default'] = 'mymail@hotmail.fr';
                 return $fields;
          }}

【问题讨论】:

  • 嗯,我的回答好像没有得到任何反馈?

标签: wordpress woocommerce product cart hook-woocommerce


【解决方案1】:

您可以通过 WC()->cart->get_cart(), 浏览购物车项目,然后您可以应用条件,如果产品 ID 存在

所以你得到:

function filter_woocommerce_checkout_fields( $fields ) {
    // Set your targeted product ID(s)
    $targeted_ids = array( 17, 30 );
    
    // Initializing
    $found = false;

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( array_intersect( $targeted_ids, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
            $found = true;
            break;
        }
    }
    
    // True
    if ( $found ) {
        // You can use this for postcode, address, company, first name, last name and such. 
        $fields['billing']['billing_email']['placeholder'] = 'mymail@hotmail.hr';
        $fields['billing']['billing_email']['autocomplete'] = 'mymail@hotmail.fr';
        $fields['billing']['billing_email']['default'] = 'mymail@hotmail.fr';
    }
    
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'filter_woocommerce_checkout_fields', 10, 1 );

相关:Change WooCommerce checkout order notes placeholder and label based on product Ids

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2018-01-07
    • 2018-06-17
    • 2017-04-27
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多