简体   繁体   中英

Display WooCommerce variable subscriptions and its variations in a drop down list

I have been creating a plugin and I am trying to pull all woo commerce subscriptions and the variations within the subscription product into a drop down list.

I have successfully pulled the top level product into the drop down list but for some reason the variations of that product don't display on my list.

Any ideas?

This is the code I believe that is adding the products to the list. Do I need to make changes to the type in order to add the variations to the list and not just the top level product?

// get product list...
          $query = new WC_Product_Query( array(
              'limit' => -1,
              'orderby' => 'date',
              'order' => 'DESC',
              'return' => 'all',
              'type' => array('variable-subscription', 'subscription')
          ) );

   

The code below will display all WooCommerce subscription products (simple subscriptions, variable subscription and their subscription available variations:

// Get all Subscription products
$subscription_products = wc_get_products( array(
    'type'  => array('variable-subscription', 'subscription'),
    'limit'     => -1,
    'orderby' => 'date',
    'order'     => 'DESC'
) );

if ( ! empty($subscription_products) ):

$html = '<div class="products-dropdown"><select name="products-select" id="products-select">
<option value="">'.__('Choose some other product').'</option>';

foreach( $subscription_products as $product ) {

    $html .= '<option value="'.$product->get_id().'">'.$product->get_name().'</option>';

    // Get Subscription variation (from variable subscription product)
    if( $product->is_type('variable-subscription') ) {
        print_pr(($product->get_id(). ' ' . $product->get_name()));

        // Loop through subscription variations
        foreach( $product->get_children() as $variation_id ) {
            // Get the WC_Product_Variation object
            $variation = wc_get_product( $variation_id );
            
            // The available subscription variation
            if( $variation->variation_is_visible() ) {
                $html .= '<option value="'.$variation_id.'">'.$variation->get_name().' (variation)</option>';
            }
        }
    }

}

$html .= '</select><p style="margin-top:1em;">';

$html .= '<a href="#" data-quantity="1" class="button alt disabled off" data-product_id="" data-product_sku="" rel="nofollow">Add to cart</a>';

// Output
echo $html . '</p></div>';

endif;

Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM