Home > Blockchain >  Make WooCommerce products featured programmatically
Make WooCommerce products featured programmatically

Time:01-29

I've tried:

update_post_meta( $product->ID, '_featured', 'true');

But it didn't seem to work

I'm seeing that that removed this as the way to update the featured status of products in WooCommerce but can't find how to do it now

Im trying to get all of my featured and non featured dokan sellers and then update all of their products as featured or non featured based on their store featured status, through something like this:

   $args = array( 'featured' => 'yes' );
   $featured = dokan_get_sellers( $args );
   
   $args = array( 'featured' => 'no' );
   $not_featured = dokan_get_sellers( $args );
   
    foreach ( $featured['users'] as $seller ) {
    $products_f = get_posts( array(
      'post_type' => 'product',
      'author' => $featured->ID,
      'posts_per_page' => -1
    ) );
    }
   foreach ( $not_featured['users'] as $seller ) {
    $products_nf = get_posts( array(
      'post_type' => 'product',
      'author' => $not_featured->ID,
      'posts_per_page' => -1
    ) );
    }
  foreach ( $products_f as $product) {

      update_post_meta( $product->ID, '_featured', 'true');
    }
 foreach ( $products_nf as $product) {

      update_post_meta( $product->ID, '_featured', 'false');
    }

Thanks

CodePudding user response:

foreach ($products_f as $product) {
    $wc_product = wc_get_product($product->ID);
    $wc_product->set_featured(1);
    $wc_product->save();
}
foreach ($products_nf as $product) {
    $wc_product = wc_get_product($product->ID);
    $wc_product->set_featured(0);
    $wc_product->save();
}

Use the built-in WooCommerce method set_featured() for updating the product.

CodePudding user response:

In this line:

$products_f = get_posts( array(
'post_type' => 'product',
'author' => $featured->ID,
'posts_per_page' => -1
) );

You are trying to access the ID of the featured seller using $featured->ID, but it should be $seller->ID, as you are looping through the array of sellers using the variable $seller.

Same goes for this line:

$products_nf = get_posts( array(
'post_type' => 'product',
'author' => $not_featured->ID,
'posts_per_page' => -1
) );

It should be $seller->ID.Try making this change and see if it works.

  • Related