如何通过元键值获取 WooComrnce 产品类别

How to get WooComrnce product category by meta key value

我有元值“old_id”的产品类别,我正在尝试创建一个函数,将 return 产品类别id 使用 old id(元键“old_id”)。

这是我试过的:

$categories = get_categories( array(
            'orderby' => 'name',
            'order'   => 'ASC',
            'hide_empty' => false, // also retrieve terms which are not used yet
            'meta_query' => array(
                array(
                   'key'       => 'old_id',
                   'value'     => $old_cat_id,
                   'compare'   => '='
                )
            ), 
        ) 
    );

使用 get_categories 不适用于 woocomrnce 类别。

然后我尝试了另一种方式:

$args = array(      
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'meta_query' => array(
                            array(
                               'key'       => 'old_id',
                               'value'     => $old_cat_id,
                               'compare'   => '='
                            )
                        ), 
            ),
        ),
    );

$query = new WP_Query($args);

出于某种原因,这个查询根本不起作用,我错过了什么吗?

add_action('init', 'get_woocommerce_product_cats');

function get_woocommerce_product_cats() {
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false;
    $cat_args = array(
        'orderby' => $orderby,
        'order' => $order,
        'hide_empty' => $hide_empty,
        'taxonomy' => 'product_cat',
        'meta_key' => 'old_id',
        'meta_value' => $old_cat_id
    );

    $product_categories = get_terms($cat_args);
    echo '<pre>';
    print_r($product_categories);
    echo '</pre>';
    exit;
}