如何将所有特色产品设置为无特色产品,然后随机选择产品并将其设置为特色产品



我正在尝试在WordPress之外创建一个脚本,该脚本将自动将所有特色产品设置为无特色产品,然后随机选择8个产品并将其设置为特色产品。

我正在处理这一部分,我获取特色产品ID,然后将其设置为无特色,但所需的结果并没有出现,有什么建议吗?

require $_SERVER['DOCUMENT_ROOT'].'/wp-config.php';
global $wpdb;
global $product;
$args = array(
'post_type'           => 'product',
'posts_per_page'      => $products,
'orderby'             => $orderby,
'order'               => $order == 'asc' ? 'asc' : 'desc',
'post__in'            => wc_get_featured_product_ids(),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ): while ( $query->have_posts() ): $query->the_post();
$product = wc_get_product( $query->post->ID );
$product->set_featured(false);
$product->save();
endwhile; wp_reset_query();endif;

要获得特色产品,您可以使用:

  • wc_get_products或wc_Product_Query

并对结果进行循环以使特色产品虚假:

// Args
$args = array(
'status'    => 'publish', // Post status
'include'   => wc_get_featured_product_ids(), // Only includes products with IDs in the array - Returns an array containing the IDs of the featured products
);
// Get products with certain arguments
$products = wc_get_products( $args );
// NOT empty
if ( ! empty ( $products ) ) {
// Loop through
foreach( $products as $product ) {
// None featured
$product->set_featured( false );
$product->save();
}
}

然后你应用类似的东西:

// Args
$args = array(
'status'    => 'publish', // Post status
'limit'     => 8, // Maximum number of results to retrieve or -1 for unlimited
'orderby'   => 'rand', // Get some random products
'exclude'   => wc_get_featured_product_ids(), // Excludes products with IDs in the array. - Returns an array containing the IDs of the featured products
);
// Get products with certain arguments
$products = wc_get_products( $args );
// NOT empty
if ( ! empty ( $products ) ) {
// Loop through
foreach( $products as $product ) {
// Featured
$product->set_featured( true );
$product->save();
}
}

OR将上述2个函数处理为1个函数:

// Args
$args = array(
'status'    => 'publish', // Post status
'limit'     => -1, // Maximum number of results to retrieve or -1 for unlimited
'orderby'   => 'rand', // Get some random products
);
// Get products with certain arguments
$products = wc_get_products( $args );
// NOT empty
if ( ! empty ( $products ) ) {
// Counter
$counter = 0;
// Loop through
foreach( $products as $product ) {
// When featured
if ( $product->get_featured() ) {
// None featured
$product->set_featured( false );
$product->save();
}
// Random products up untill 8 and none featured
if ( $counter < 8 && ! $product->get_featured() ) {
// Make featured true
$product->set_featured( true );
$product->save();
// Counter = counter + 1
$counter ++;
}
}
}

相关内容

  • 没有找到相关文章

最新更新