添加基于 WooCommerce 产品价格的免费送货通知

问题描述

我正在尝试为两种情况制作自定义代码(同时考虑简单和可变产品):

  • 1 个免费送货通知,如果价格低于 25 欧元
  • 1 个免费送货通知,如果价格高于 25 欧元

这是我的代码尝试:

/**
 * FREE SHIPPING NOTICE IF PRICE BELOW 25 €
 */
add_action( 'woocommerce_single_product_summary','custom_text1',15 );
function custom_text1() {
    // We retrieve the minimum of the product
    $min_price = $product->get_variation_price( 'min',true );

    // If price is lower than 25,show first label
    if ($min_price < 25) {
        print '<p class="custom_text1">+ livraison gratuite à partir de 25 €</br>(Belgique,France,Pays-Bas)</p>';
    }
}

/**
 * FREE SHIPPING NOTICE IF PRICE ABOVE 25 €
 */
add_action( 'woocommerce_single_product_summary','custom_text2',15 );
function custom_text2() {
    // We retrieve the minimum of the product
    $min_price = $product->get_variation_price( 'min',true );

    // If price is higher than 25,show second label
    if ($min_price >= 25) {
        print '<p class="custom_text2">+ livraison gratuite</br>(Belgique,Pays-Bas)</p>';
    }
}

我没有足够的经验,它不起作用。

我做错了什么?有人可以帮助我更好地实现这一目标吗?

解决方法

需要定义 WC_Product 对象 $product,您可以将两个函数合二为一,用于可变产品和其他产品类型,例如:

add_action( 'woocommerce_single_product_summary','custom_single_product_summary_text',15 );
function custom_single_product_summary_text() {
    global $product;
    
    $price_threshold = 25;

    // Avoid 'cadeaux' product category
    if( has_term( array('Cadeaux'),'product_cat',$product->get_id() ) ) {
        return;
    }
    
    if( $product->is_type('variable') ) {
        $price = $product->get_variation_price( 'min',true ); // Min price
    } else {
        $price = wc_get_price_to_display( $product );
    }


    // If price is lower than 25
    if ( $price < $price_threshold ) {
        $message = __("+ livraison gratuite jusqu'à 25€</br>(Belgique,France,Pays-Bas)","text_domain");
    } 
    // If price is up to 25
    else {
        $message = __("+ livraison gratuite à partir de 25 € </br>(Belgique,"text_domain");
    }
    echo '<p class="custom_text1">' . $message . '</p>';
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...