0

I'm trying to hide products in Woocommerce according to the user ID who published them.

I have created the following code but it doesn't work well.

function Products_for_vendor() {
$args     = array( 'post_type' => 'product', 'post_author' => '2' );
$products = get_posts( $args );

    foreach ($products as $product->ID) {

        $post_id = $product->ID

        $terms = array( 'exclude-from-catalog', 'exclude-from-search' );
        wp_set_object_terms( $post_id, $terms, 'product_visibility', false );

    }

}

add_action( 'init', 'Products_for_vendor' );

to hide the post I extracted the code mentioned in this query: Change product visibility via PHP on Woocommerce 3+

Any help or comment is well received.

Thanks in advance.

Noe_Mares
  • 95
  • 2
  • 9

1 Answers1

0

You shouldn't be changing things like this directly - WooCommerce has special functions to ensure future compatibility with any database structural changes, and to ensure that product data is properly synchronised within its internal caches.

Instead, inside of your foreach loop, use this:

// Get an instance of the product
$theproduct = wc_get_product($product->ID);
// Change the product visibility (options are: 'hidden', 'visible', 'search' and 'catalog'.
$theproduct->set_catalog_visibility('hidden');
// Finally, save and sync the product changes
$theproduct->save();
Peter HvD
  • 1,623
  • 1
  • 7
  • 14