Home > Net >  Remove out of stock products, add date condition with wpdb
Remove out of stock products, add date condition with wpdb

Time:06-25

This works for me, but I need the date condition. If post modified date is 10 days ago, that's true, otherwise false, how can I do that?

add_action('init', 'automatically_trash_sold_items_in_woocommerce_callback');
function automatically_trash_sold_items_in_woocommerce_callback() {

    // Get any existing copy of our transient data
    if ( false === ( $automatically_trash_sold_items_in_woocommerce = get_transient( 'automatically_trash_sold_items_in_woocommerce' ) ) ) {
        
        // 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='_stock_status' AND PM.meta_value='outofstock'");

        set_transient( 'automatically_trash_sold_items_in_woocommerce', true, 12 * HOUR_IN_SECONDS );
      }
}

CodePudding user response:

You can follow the same concept from the auto delete draft wp function https://developer.wordpress.org/reference/functions/wp_delete_auto_drafts/

This should filter posts with modified date more than 10 days ago.

   add_action('init', 'automatically_trash_sold_items_in_woocommerce_callback');
    function automatically_trash_sold_items_in_woocommerce_callback() {
    
        // Get any existing copy of our transient data
        if ( false === ( $automatically_trash_sold_items_in_woocommerce = get_transient( 'automatically_trash_sold_items_in_woocommerce' ) ) ) {
            
            // 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='_stock_status' AND PM.meta_value='outofstock' AND DATE_SUB( now(), INTERVAL 10 DAY ) > p.post_modified");
    
            set_transient( 'automatically_trash_sold_items_in_woocommerce', true, 12 * HOUR_IN_SECONDS );
          }
  • Related