简体   繁体   中英

Hide products published by certain users on Woocommerce

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM