Home > Back-end >  How to get woocomrnce product category by meta key value
How to get woocomrnce product category by meta key value

Time:02-17

I have product categories with meta value "old_id" , im trying to make a function that will return the new product category id using the old id (with meta key "old_id").

this is what i have tried :

$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'   => '='
                )
            ), 
        ) 
    );

using get_categories does not work for woocomrnce categories.

then i tried another way :

$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);

for some reason this query does not work at all, did i miss anything?

CodePudding user response:

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;
}
  • Related