控制 WooCommerce javascript 函数的执行

Controlling execution of WooCommerce javascript functions

提问人:Rip 提问时间:11/15/2023 最后编辑:LoicTheAztecRip 更新时间:11/15/2023 访问量:36

问:

删除条件或将条件应用于 WooCommerce JavaScript 函数的正确方法是什么?

特别是,我想停止所有股票消息。如果我可以根据 DOM 中可用的类或属性停止消息,那就更好了。

默认情况下,当变体库存降至零时,WooCommerce 会删除此元素的所有后代:

<div class="woocommerce-variation single_variation"></div>

并插入以下元素:

<p>Sorry, this product is unavailable. Please choose a different combination.</p>

我删除了模板文件中的 p 元素文本:variation.php,所以现在 WooCommerce 插入了一个空的 p 元素。

看起来此行为是在此 js 文件中启动的:添加到购物车变体.js

禁止删除和插入div.single_variation中元素的正确方法是什么,最好是基于分配给这些元素之一的 css 类或分配给 form.cart 祖先元素的属性值?

JavaScript PHP WordPress 模板 woocommerce

评论


答:

0赞 LoicTheAztec 11/15/2023 #1

删除“对不起,此产品不可用。请选择不同的组合。文本,您可以简单地使用以下内容:

add_filter( 'woocommerce_get_script_data', 'remove_variation_unavailable_text_js', 10, 2 ); 
function remove_variation_unavailable_text_js( $params, $handle )  {
    if( 'wc-add-to-cart-variation' === $handle ) {
        $params['i18n_unavailable_text'] = '';
    }
    return $params;
}

代码位于子主题的函数.php文件中(或插件中)。

所有这些变体库存消息都由 WC_Frontend_Scripts 类处理,如下所示:

// From line 583 to line 593
case 'wc-add-to-cart-variation':
    // We also need the wp.template for this script :).
    wc_get_template( 'single-product/add-to-cart/variation.php' );

    $params = array(
        'wc_ajax_url'                      => WC_AJAX::get_endpoint( '%%endpoint%%' ),
        'i18n_no_matching_variations_text' => esc_attr__( 'Sorry, no products matched your selection. Please choose a different combination.', 'woocommerce' ),
        'i18n_make_a_selection_text'       => esc_attr__( 'Please select some product options before adding this product to your cart.', 'woocommerce' ),
        'i18n_unavailable_text'            => esc_attr__( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ),
    );
    break;

因此,无需对模板文件进行更改。variation.php

评论

0赞 Rip 11/18/2023
谢谢。“woocommerce_get_script_data”过滤器的参数“i18n_unavailable_text”不会替换变体中此行生成的文本.php模板:<p><?php esc_html_e( '对不起,此产品不可用。请选择其他组合>><。
0赞 Rip 11/18/2023
我能够通过将此行替换为自定义变体模板中的元素<script type=“text/template” id=“tmpl-variation-template”>的内容来抑制此消息.php。我想知道我是否缺少过滤器或“woocommerce_get_script_data”参数,这些参数将在没有自定义模板的情况下替换这行代码。