Search code examples
wordpresswoocommercewoocommerce-subscriptions

Woo subscriptions - Request not working get_posts()


My idea is to get all active (status - wc-active) subscriptions.

 // Get all active subscriptions
        $active_subscriptions = get_posts( array(
    
            'post_type'   => 'shop_subscription', // Subscription post type
            'post_status' => 'wc-active', // Active subscription
            'fields'      => 'ids', // return only IDs (instead of complete post objects)
        ) );

enter image description here

But I always get the same result. But the result is not correct.

array(3) { [0]=> int(6518) [1]=> int(6514) [2]=> int(6512) }

Tried to use this function wcs_get_subscriptions() from a plugin. Get an error "Fatal error: Uncaught Error: Call to a member function get_order() on null ...."

// Get all active subscriptions
$active_subscriptions = wcs_get_subscriptions( array(
    'subscription_status' => 'wc-active'
) );

https://github.com/riclain/woocommerce-subscriptions/blob/b0dd2efd869b0639ad54131fba9c13b4ed5a09a2/wcs-functions.php#L332


Solution

  • If you have an error like mine that the functions from WordPress (Woocommerce) do not work. You can use SQL.

    My solution is this.

        function get_active_subscriptions_and_upcoming_renewals() {
        global $wpdb;
    
        // Get active subscriptions
        $active_subscriptions = $wpdb->get_results(
            "SELECT posts.ID FROM {$wpdb->posts} AS posts WHERE posts.post_type = 'shop_subscription' AND posts.post_status = 'wc-active';"
        );
    
        $active_subs_ids = [];
        foreach ( $active_subscriptions as $active_subs ) {
            array_push( $active_subs_ids, (int)$active_subs->ID );
        }
    
        $active_subs_string = implode( ',', $active_subs_ids);
    // Get subscriptions that will automatically renew after 2 days
    
        $upcoming_renewals = $wpdb->get_results(
    
                "
               SELECT post_id FROM wp_postmeta WHERE post_id IN ({$active_subs_string}) AND meta_key = '_schedule_next_payment' AND DATE(meta_value) <= DATE(DATE_ADD(NOW(), INTERVAL 2 DAY));
                "
    
        );
    
        // Return results
        return array(
            'active_subscriptions' => $active_subs_ids,
            'upcoming_renewals'    => $upcoming_renewals,
        );
    }