【问题标题】:A Wordpress cronjob to cancel WC orders for a product that was deleted?用于取消已删除产品的 WC 订单的 Wordpress cronjob?
【发布时间】:2019-02-02 13:39:57
【问题描述】:

我有一个项目,用户实际上可以删除他们自己的待售虚拟产品,并且在删除时该产品实际上可能有一些活动订单。我认为最好的解决方案是添加一个每 10 分钟运行一次的 cronjob,使用真正的 cron,通过 crontab,而不是我已经制定的 Wordpress 虚拟 cron - 但问题是,我如何获得所有订购产品,然后将所有这些产品的状态更改为已取消而不是删除它们,以备后用。

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: wordpress woocommerce cron


    【解决方案1】:

    所以,解决了...更安全且通常更好的方法。您不是使用 cronjob,而是在删除后挂钩,当实际删除产品时,您执行所需的查询。您会发现所有未完成的附加订单,并取消这些即将到来的/待处理的订单。

    function get_order_ids_by_product_id( $product_id, $order_status = array( 'wc-completed' ) ){
        global $wpdb;
        $results = $wpdb->get_col("
            SELECT order_items.order_id
            FROM {$wpdb->prefix}woocommerce_order_items as order_items
            LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
            LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
            WHERE posts.post_type = 'shop_order'
            AND posts.post_status NOT IN ( '" . implode( "','", $order_status ) . "' )
            AND order_items.order_item_type = 'line_item'
            AND order_item_meta.meta_key = '_product_id'
            AND order_item_meta.meta_value = '$product_id'
        ");
        return $results;
    }
    
    add_action( 'before_delete_post', 'check_for_active_orders' );
    function check_for_active_orders($post_id){
        $WC_Product = wc_get_product( $post_id );
        $orders_ids = get_order_ids_by_product_id( $post_id );
        if(count($orders_ids) > 0){
          foreach($orders_ids as $oid){
            $order = new WC_Order($oid);
            $order->update_status('cancelled', 'This product has been removed.');
          }
        }
    }
    

    希望它会在不久的将来对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      相关资源
      最近更新 更多