Chad Berlean
Chad Berlean

Reputation: 13

How do I get the category name or id of a product of a woocommerce order

I have the function below which works to change the role of a user when they buy certain products, but instead of listing out specific product IDs, I'd like to just use the category name or id of those products. That way, if we add a new product in that category, I don't have to remember to add it to this function. This function is specific to a certain category, so it doesn't matter if people have other products from other categories in the order.

function lgbk_add_member( $order_id ) {
    $order = new WC_Order( $order_id );
    $items = $order->get_items();

    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];

        if ( $order->user_id > 0 && $product_id == '7' ) {
            update_user_meta( $order->user_id, 'paying_customer', 1 );
            $user = new WP_User( $order->user_id );

            // Remove role
            $user->remove_role( 'expired' ); 

            // Add role
            $user->add_role( 'customer' );
            }
        }
    }

    add_action( 'woocommerce_order_status_completed', 'lgbk_add_member' );

Upvotes: 1

Views: 9947

Answers (2)

Amritosh pandey
Amritosh pandey

Reputation: 404

You can get product category name using this function -

function get_product_category_name_by_id( $category_id ) {
  $term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
  return $term['name'];
}

$product_category = get_product_category_name_by_id( $your_category_id );

Thanks!

Upvotes: 0

Maha Dev
Maha Dev

Reputation: 3965

You have to use wp_get_post_terms to get category id of any product like this :

$term_list = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));

I am just fetching id's of categories assigned to this particular product, you can fetch name also.

Upvotes: 2

Related Questions