【问题标题】:Customizing add-to-cart messages based on the product IDs in WooCommerce 3根据 WooCommerce 3 中的产品 ID 自定义添加到购物车的消息
【发布时间】:2017-08-19 08:26:55
【问题描述】:

我的网站上有两种产品,并且想在将不同产品添加到购物车时显示不同的消息(在消息中我想使用 HTML)。现在它显示Product successfully added to cart. 我在我孩子的 function.php 中使用了这段代码,它正在工作,但没有给我我真正想要的。

add_filter ( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 );
function wc_add_to_cart_message_filter($message, $product_id = null) {
   $titles[] = get_the_title( $product_id );

$titles = array_filter( $titles );
$added_text = sprintf( _n( '%s has been successfully added to your Basket.', '%s have been added to your Basket.', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) );

$message = sprintf( '%s <a href="%s" class="button">%s</a>',
               esc_html( $added_text ),
               esc_url( wc_get_page_permalink( 'cart' ) ),
               esc_html__( 'View Cart', 'woocommerce' ));

return $message;
}

【问题讨论】:

  • 我有两个产品,分别是 p1 和 p2,如果其中一个产品被添加到购物车,它会显示一条消息“您的产品已添加到购物车和一个‘查看购物车’按钮”。我想在添加不同产品时显示不同的消息,例如如果我将 p1 添加到购物车它应该显示“message1”,如果将 p2 添加到购物车它应该显示“message2”。我希望现在它是有意义的。

标签: php wordpress woocommerce product messages


【解决方案1】:

由于 WooCommerce 3 wc_add_to_cart_message 已被 wc_add_to_cart_message_html 取代,因为它现在已被弃用。根据产品 ID(甚至产品类别)进行此工作的自定义添加到购物车消息的正确方法:

add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_html_filter', 10, 2 );
function wc_add_to_cart_message_html_filter( $message, $products ) {

    foreach( $products as $product_id => $quantity ){

        // (If needed) get the WC_Product object
        $product = wc_get_product( $product_id );
        // The product title
        $product_title = $product->get_title();

        // Set Here a product category Id, name or slug (for example, if needed)
        $product_category = "Clothing";
        if( has_term( 'clothing', 'product_cat', $product_id ) ){
            return __("My custom message for product category \"$product_category\" for $product_title ($product_id)", "woocommerce");
        }

        // Set HERE your first Product ID
        if( $product_id == 37 ){
            return __("My custom message 1 for $product_title ($product_id)", "woocommerce");
        }
        // Set HERE your Second Product ID
        elseif( $product_id == 40 ){
            return __("My custom message 2 for $product_title ($product_id)", "woocommerce");
        }
    }
    return $message;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

在 WooCommerce 3+ 中测试并有效。

【讨论】:

    【解决方案2】:

    如果有人看不到更改,请检查是否有任何插件已触发此过滤器,因此请确保 $priority 更高

    add_filter( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-08
      • 2021-06-10
      • 2020-09-01
      • 2015-05-27
      • 1970-01-01
      • 2018-07-23
      • 2015-12-04
      • 2023-03-09
      相关资源
      最近更新 更多