Reputation: 139
I have the following code:
foreach ($loop->posts as $product) {
$currentPrice = get_post_meta($product->ID, '_regular_price', true);
update_post_meta( $product->ID, '_price', $currentPrice );
update_post_meta( $product->ID, '_regular_price', $currentPrice );
delete_metadata('post', $product->ID, '_sale_price');
if(in_array($i, $random_product)) {
$discount = rand(10,25) / 100;
$salePrice = $discount * $currentPrice;
$salePrice = ceil($currentPrice - $salePrice);
if($salePrice == $currentPrice) {
$salePrice = $currentPrice - 1;
}
if($currentPrice != '' || $currentPrice == '0') {
update_post_meta($product->ID, '_sale_price', $salePrice);
update_post_meta( $product->ID, '_price', $salePrice );
echo "Sale Item $i / Product ID $product->ID / Current Price $currentPrice / Sale Price $salePrice \n";
}
}
$i++;
}
Basically what I am trying to do is take every item through my store, loop it and if it's in my array (which is just a random generated array of product IDs) it should set those to be on sale, and make sure every other product is not on sale.
However, when I do that... for whatever reason all my variable products then show up as unavailable until I go into their product page and click Variations -> Set Status -> In Stock
I thought I would be clever and change it to managed stock and have 999 products available in stock but still creates the same problem.
The thing is, I don't change the stock with this only the price... however it is this code I have run it manually and it triggers the problem.
Any thoughts?
Upvotes: -1
Views: 1071
Reputation: 253784
You should try to use CRUD methods newly introduced since WooCommerce 3 instead of using WordPress post meta functions.
I have also made some changes in your code, but is not possible to test that as your question code is incomplete. Try something like the following:
foreach ( $loop->posts as $post ) {
// Get an instance of the product object
$product = wc_get_product($post->ID);
$changes = false;
// Get product regular and sale prices
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
if( ! empty($sale_price) || $product->is_on_sale() ) {
// Empty product sale price
$product->set_sale_price('');
// Set product active price back to regular price
$product->set_price($regular_price);
$changes = true;
}
if( in_array( $i, $random_product ) ) {
// Calculate a ramdom sale price for the current ramdom product
$discount_rate = (100 - rand(10, 25)) / 100;
$sale_price = ceil($discount_rate * $regular_price);
// Set product active price and sale price
$product->set_sale_price($sale_price);
$product->set_price($sale_price);
printf( __("Sale Item %s / Product ID %s / Current Price %s / Sale Price %s \n"),
$i, $post->ID, wc_price($regular_price), wc_price($sale_price) );
$changes = true;
}
$i++;
if( $changes ){
// Save the product data
$product->save();
}
}
Untested
Upvotes: 1