I have created code as below and the focus part is PM.meta_key !='_price'
and I don't know how true it is, it didn't work but it's also possible to remove all products otherwise, I need a correct way.
Also here is a picture, some products don't have the "_price" key and this way the product looks very bad, the strange thing is that they are still in stock.
Here is an example photo.
add_action( 'init', 'automatically_trash_instock_empty_price' );
function automatically_trash_instock_empty_price() {
// Get any existing copy of our transient data
if ( false === ( $automatically_trash_instock_empty_price = get_transient( 'automatically_trash_instock_empty_price' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
global $wpdb;
$wpdb->query( "UPDATE {$wpdb->posts} P JOIN {$wpdb->postmeta} PM ON P.ID = PM.post_id SET P.post_status='trash' WHERE P.post_type='product' and PM.meta_key != '_price'" );
set_transient( 'automatically_trash_instock_empty_price', true, 1 * HOUR_IN_SECONDS );
}
}
CodePudding user response:
I know you asked for MySQL query but why not use native functions for this? You can query all your products and foreach
create a product object using the following function:
$product = wc_get_product( $post_id );
And after that you will be able to access all product's data. All available methods can be found here, but the ones you probably need are:
$product->get_regular_price();
$product->get_sale_price();
$product->get_price();
Then check if $product->get_price();
is null, empty and/or zero and just:
wp_trash_post($product->get_id());
Finally, you could also set this up as a cron job to run daily/weekly and clean up your products regularly.
EDIT
As per your comments here is a full working example of a scheduled function via wp-cron to do what you asked regularly:
// Your scheduled function
function trash_products_without_price_stock() {
$get_all = new WP_Query(
array(
'post_type' => 'product',
'posts_per_page' => -1,
)
);
if ( $get_all->have_posts() ) :
while ( $get_all->have_posts() ) :
$get_all->the_post();
// Start : Your conditionals here
if ( ! get_post_meta( get_the_ID(), '_price', true ) && get_post_meta( get_the_ID(), '_stock', true ) ) {
wp_trash_post( get_the_ID() );
}
// End
endwhile;
wp_reset_postdata();
endif;
}
// Schedule Cron Job Event
if ( ! wp_next_scheduled( 'clean_my_products' ) ) {
// here you can use 'hourly', 'twicedaily', 'daily', and 'weekly'
wp_schedule_event( time(), 'daily', 'clean_my_products' );
}
add_action( 'clean_my_products', 'trash_products_without_price_stock' );
Put the above in functions.php