【问题标题】:Display "In Stock" notice for WooCommerce variations with no Managed Stock显示没有托管库存的 WooCommerce 变体的“库存”通知
【发布时间】:2020-07-07 15:20:31
【问题描述】:

我需要针对特定​​情况的帮助。在 WooCommerce 中,如果为简单的产品或变体启用了“管理库存”,则会在产品页面中显示通知 => 例如 [this example][1]

但是,如果未启用“管理库存”,则没有通知,我觉得很遗憾,因为即使我不管理库存数量,我仍然想通知我的客户它正好有库存。

我找到了以下代码。对于简单的产品,它可以正常工作。但是,对于可变产品,即使在选择变体之前也会显示此消息。这当然不行,这个代码只有在选择了一个变体后才会显示。

有人可以帮我解决这个问题吗?对于可变产品,仅在选择特定变体之后才应显示此消息。

我已经制作了一个视频捕捉以更具说明性:https://sgevcen.tinytake.com/tt/NDQzNTU2OF8xNDAyNTU2NA

function mycustom_shop_display_stock() {

    global $product;

    if ( !$product->get_manage_stock() && $product->is_in_stock() ) {
        echo '<p class="stock in-stock">In Stock</p>';
    }
}
add_action( 'woocommerce_before_add_to_cart_button', 'mycustom_shop_display_stock', 11 );


  [1]: https://i.stack.imgur.com/aFnN1.png

【问题讨论】:

标签: php wordpress woocommerce hook-woocommerce stock


【解决方案1】:

请尝试以下方法,以便仅针对可变产品的变体(以及简单产品)显示您的自定义库存可用性:

add_filter( 'woocommerce_get_stock_html', 'filter_wc_get_stock_html', 10, 2 );
function filter_wc_get_stock_html( $html, $product ) {
    if ( ! $product->is_type('variable') && ! $product->get_manage_stock() && $product->is_in_stock() ) {
        $html = '<p class="stock in-stock">' . __( "In Stock", "woocommerce" ) . '</p>';
    }

    return $html;
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。


要排除某些产品类别,请使用以下(与您的评论相关):

add_filter( 'woocommerce_get_stock_html', 'filter_wc_get_stock_html', 10, 2 );
function filter_wc_get_stock_html( $html, $product ) {
    // Here define the product categories to be excluded (can be term Ids, slugs or names)
    $terms_excl = array('hoodies', 'albums');

    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    if ( ! $product->is_type('variable') && ! $product->get_manage_stock() && $product->is_in_stock()
    && ! has_term( $terms_excl, 'product_cat', $product_id ) ) {
        $html = '<p class="stock in-stock">' . __( "In Stock", "woocommerce" ) . '</p>';
    }

    return $html;
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。


相关话题:Display custom stock message if "Manage Stock" is not enabled in WooCommerce

【讨论】:

  • 在本主题中,是否可以排除受此代码影响的某些产品(属于产品类别a、cateogryb 和categoryc)?
  • 我是这个平台的新手,所以如果我不熟悉它的所有工作方式,请道歉。我刚刚“接受了答案”并且我也“说谢谢”:) 但事实上我没有使用上面的代码,我正在使用这个:stackoverflow.com/questions/60749190/… 所以应该在这个代码上完成排除跨度>
  • 我刚刚测试了为排除提供的代码,但它似乎不起作用。您可以查看我在其中显示(缓存已清除)的视频捕获:sgevcen.tinytake.com/tt/NDQ0NzE1OF8xNDA2MjMwOA 我尝试通过 slugs 和 ID 定义类别,但两者都没有改变任何东西。通知很好地显示给所有人,但排除不起作用。你能帮忙吗?谢谢
  • 嗨 LoicTheAztec,您有时间检查我下面的答案吗?谢谢
  • @gevcen 那是我的代码中的一个愚蠢的错误......它现在可以工作了。您能否删除您的答案并清理所有旧的 cmets,因为相关代码只是与原始问题无关的添加。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 2020-10-28
  • 2022-11-17
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多