使用add_filter hook自定义WooCommerce通知

时间:2016-06-14 22:47:59

标签: php wordpress woocommerce cart hook-woocommerce

我正在尝试自定义WooCommerce通知。 这是我要替换的通知:

wc_add_notice( sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() ), 'error' )

基于这个有用的答案WooCommerce Notice Messages, how do I edit them?,我提出了这个问题:

function my_woocommerce_membership_notice( $error ) {
    if ( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.' == $error ) {
        $error = '%s has been removed from your cart because you added a membership product. Please complete the membership purchase first.';
    }
    return $error;
}

add_filter( 'woocommerce_add_error', 'my_woocommerce_membership_notice' );

这导致HTTP500错误,我无法弄清楚究竟是为什么。

谢谢!

1 个答案:

答案 0 :(得分:2)

在互联网上搜索这个问题,似乎有很多人在尝试使用类似的东西时遇到严重的类似错误...

此错误消息在docs clearly state第238行设置。

查看includes/class-wc-cart.php中的WC 2.6版源代码,$message正在处理2个变量:$notice_typesprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() )

因此,对于 $ message 变量,我们有:'%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.'
而不仅仅是:
%s

sprintf() $_product->get_title()用来替换为 %s 值的字符串变量。但是你不能在这里使用 '%s has been… 了。
这可能是您的错误问题的原因。而不是'An item has been…尝试strpos()

然后基于includes/wc-notice-functions.php,在条件中使用function my_woocommerce_membership_notice( $message ) { if (strpos($message,'has been removed from your cart because it can no longer be purchased') !== false) { $message = 'An item has been removed from your cart because you added a membership product. Please complete the membership purchase first.'; } return $message; } add_filter( 'woocommerce_add_error', 'my_woocommerce_membership_notice' ); php函数,我编译了这个片段,没有任何保证:

focusInvalid