Create Custom Add To Cart For Multiple Simple Products In Dropdown.

In this article, we learn how to set products into dropdown and how to use them as add-to-cart products.

Follow below steps to set the product into the dropdown.

Step-1: Create a shortcode and add a simple select option.

function product() {
  ob_start();
  ?>
  <select class="donate-shop-main">
    <option>product</option>    
  </select>
  <?php
  return ob_get_clean();
}
add_shortcode( 'product_shortcode', 'product' );

Step-2: Get product using wp_query and set it as an option.

<?php
  $product = array(
    'post_type'   => 'product',
    'posts_per_page'=> '',
    'post_status' => 'publish',
    'orderby'       => 'date',
    'order'         => 'DESC'
  );

  $product_posts = new WP_Query( $product );
  if ( $product_posts->have_posts() ) :
    while ( $product_posts->have_posts() ) : $product_posts->the_post();
      ?>
      <option class="item-product donate-shop-wrap" value="?add-to-cart=<?php echo get_the_ID() ?>">
        <?php 
        $post_meta_value_shop = wc_get_product( get_the_ID() );
        $price = $post_meta_value_shop->get_price_html();
        ?>
        <div class="donate-shop-title"><?php the_title(); ?>&nbsp;&nbsp;<?php echo $price ?></div>
      </option> 
      <?php
    endwhile;
  else:
    ?>
    <option class="item-product donate-shop-wrap">No product found...</option>
<?php endif;

Step-3: Set on change by location functionality in the select option.

<select class="donate-shop-main" onchange="location = this.value;">

Here is the full code.

function product() {
  ob_start();
?>
<select class="donate-shop-main" onchange="location = this.value;">
  <option>product</option>
    
  <?php
  $product = array(
    'post_type'   => 'product',
    'posts_per_page'=> '',
    'post_status' => 'publish',
    'orderby'       => 'date',
    'order'         => 'DESC'
  );

  $product_posts = new WP_Query( $product );
  if ( $product_posts->have_posts() ) :
    while ( $product_posts->have_posts() ) : $product_posts->the_post();
      ?>
      <option class="item-product donate-shop-wrap" value="?add-to-cart=<?php echo get_the_ID() ?>">
        <?php 
        $post_meta_value_shop = wc_get_product( get_the_ID() );
        $price = $post_meta_value_shop->get_price_html();
        ?>
        <div class="donate-shop-title"><?php the_title(); ?>&nbsp;&nbsp;<?php echo $price ?></div>
      </option> 
      <?php
    endwhile;
  else:
    ?>
    <option class="item-product donate-shop-wrap">No product found...</option>
  <?php endif;
    wp_reset_postdata();
    ?>
    
</select>
<?php
  return ob_get_clean();
}
add_shortcode( 'product_shortcode', 'product' );

Step-4: Use created shortcode where you want to add dropdown option,

Here is the result.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories