簡體   English   中英

以編程方式制作 WooCommerce 產品

[英]Make WooCommerce products featured programmatically

我試過了:

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

但它似乎沒有用

我看到在 WooCommerce 中刪除了此作為更新產品特色狀態的方式,但現在找不到如何操作

我試圖獲得我所有的特色和非特色 dokan 賣家,然后根據他們的商店特色狀態將他們的所有產品更新為特色或非特色,通過這樣的事情:

   $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');
    }

當前代碼:


add_action( 'set_featured_hook', 'set_featured' );
function set_featured(){
   $args_featured = array( 'featured' => 'yes' );
   $featured = dokan_get_sellers( $args_featured );
   
   $args_nf = array( 'featured' => 'no' );
   $not_featured = dokan_get_sellers( $args_nf );
   
    foreach ( $featured['users'] as $seller ) {
    $products_f = get_posts( array(
      'post_type' => 'product',
      'author' => $seller->ID,
      'posts_per_page' => -1
    ) );
    }
    
    foreach ( $not_featured['users'] as $seller ) {
    $products_nf = get_posts( array(
      'post_type' => 'product',
      'author' => $seller->ID,
      'posts_per_page' => -1
    ) );
    }
 foreach ($products_f as $product) {
    $wc_product_f = wc_get_product($product->ID);
    $wc_product_f ->set_featured(1);
    $wc_product_f ->save();
}

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

謝謝

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

使用內置的 WooCommerce 方法set_featured()更新產品。

在這一行中:

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

您正在嘗試使用 $featured->ID 訪問特色賣家的 ID,但它應該是$seller->ID ,因為您正在使用變量 $seller 遍歷賣家數組。

這條線也一樣:

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

它應該是 $seller->ID。嘗試進行此更改並查看它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM