根据这里的代码https://www.businessbloomer.com/woocommerce-stock-quantity-suffix-e-g-sq-in-kg-boxes-etc/,我有下面的代码,允许我为WooCommerce的产品数量添加后缀.一切都可以通过简单的产品完美运行.对于可变产品,即使我设置了另一个后缀,它也只显示默认后缀.例如,不显示"Bax",而是显示"m2".如何使其与可变产品一起工作?

提前感谢!

add_filter( 'woocommerce_format_stock_quantity', 'wc_stock_quantity_suffix', 9999, 2 );

function wc_stock_quantity_suffix( $stock_quantity, $product ) {
    $categories = get_the_terms( $product->get_id(), 'product_cat' );

    if ( $categories && ! is_wp_error( $categories ) ) {
        $category_slug = $categories[0]->slug;

        switch ( $category_slug ) {
            case 'phone':
                $stock_quantity .= ' buc.';
                break;
            case 'accessories':
                $stock_quantity .= ' bax';
                break;
            case 'milk':
                $stock_quantity .= ' l';
                break;
            
            default:
                
                $stock_quantity .= ' m<sup>2</sup>';
                break;
        }
    } else {
        // If there are no categories, we use the default suffix
        $stock_quantity .= ' m<sup>2</sup>';
    }

    return $stock_quantity;
}

推荐答案

对于可变产品,product_cat个术语与母产品(包含个体变体的可变产品)相关,而不是个体变体本身.然而,woocommerce_format_stock_quantity提供的是产品变体,而不是母产品.因此,您需要在这些情况下检索母产品,并在该情况下检索get_the_terms.

您可以使用WC_Product::get_parent_id方法检索父产品id:

add_filter( 'woocommerce_format_stock_quantity', 'wc_stock_quantity_suffix', 9999, 2 );

function wc_stock_quantity_suffix( $stock_quantity, $product ) {

    if ($parent_id = $product->get_parent_id()) $product = wc_get_product($parent_id);

    $categories = get_the_terms( $product->get_id(), 'product_cat' );

    // Your category logic goes here ...

    return $stock_quantity;

}

Php相关问答推荐

p a/a/p的x路径 Select ,但不是p somethext a链接/a或某些文本/p>

PHP如何将ARRAY_MAP与Reset()配合使用

保存PHP条带以备将来使用,不显示用户界面

如何在函数中定位WooCommerce产品循环

根据WooCommerce购物车页面中的自定义 Select 添加费用

FlySystem v3:使用本地适配器时出现问题

如何使用barryvdh/laravel-Snappy在两个打印页面上将表格分成两部分?

Codeigniter 4中的未定义变量$HOME

Wordpress,配置一周第一天选项

计算添加到购物车的点击次数并将其显示在 WooCommerce 管理产品列表中

使用产品自定义字段作为 WooCommerce 中特定用户角色的折扣百分比

如何为自定义帖子类型的自定义角色提供功能

从插件更改主题功能,function_exists 不起作用

添加或删除优惠券后自动刷新 WooCommerce checkout 表单字段

计算数组中连续值的数量

htaccess Rewriterule 无法以任何方式工作

保留 .htaccess 中的符号登录 URL

来自 GoDaddy 的邮箱在 Gmail 中显示为via

在 Laravel、Vuejs 和 Inertia 中配置 TypeScript 的问题

如何在光速网络服务器中使用 apache ..htaccess