PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How to get WooComrnce product category by meta key value

 May 16, 2022     categories, hook-woocommerce, php, woocommerce, wordpress     No comments   

Issue

I have product categories with the meta value "old_id", I'm 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?


Solution

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


Answered By - mujuonly
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing