Support » Plugin: WooCommerce » Get product category ID from product ID

  • Resolved jj

    (@jjjoel)



    I’m trying to develop a plugin that involves updating stock levels based on a JSON feed. I want to trash off any products that are in a “Clearance” category once they become 0 stock.

    The problem I’m running into is with getting the product’s category to use in an ‘if’ statement. I’ve tried using wp_get_post_terms, but it returns an error as if the ‘product_cat’ taxonomy doesn’t exist.

    I’m quite new to PHP and WordPress development, so I’m probably just doing something super dumb. Do I need to load in woocommerce’s taxonomy somehow into my plugin? Or should it work to use something like:

    <?php
    
    $cat_ids = wp_get_post_terms($product_id, 'product_cat', array('fields'=>'ids'));
    
    if (in_array($category_id, $cat_ids->taxonomy_id)
    {
    $post_trash = array(
    'ID' => $product_id,
    'post_status' => 'trash'
    );
    wp_update_post($post_trash);
    }
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Hello Joel

    Based on a Product ID, here is your revisited and working code that will set any product from “Clearance” product category with a “pending” post status (instead of “trash”):

    // Targeting products in "Clearance" product category (from product ID)
    if ( has_term( 'Clearance', 'product_cat', $product_id ) )
    {
    	// Get an instance of the WC_Product object
    	$product_obj = wc_get_product( $product_id );
    	
    	// targetting products with no stock quantity
    	if( 0 == $product_obj->get_stock_quantity() )
    		wp_update_post( array(
    			'ID' => $product_id,
    			'post_status' => 'pending' // pending status
    		) );
    }

    This should work as you expect. If you need the “trash” post_status you can just change it in this codeā€¦

    Cheers

    (You should now mark this question as “solved”)

    That worked, thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get product category ID from product ID’ is closed to new replies.