Auto load product variable after selecting product title woocommerce

Viewed 25

I am trying to have a form where woo product title will show up in select field as dropdown, after selecting one all others information like variable etc. I just have to know how All Product Title can be pulled in select field by foreach . Once I get the idea how to bring out all product title from while loop then should be same to get others meta

<php
global $product;
    <ul class="products">
        <?php
            $args = array(
                'post_type' => 'product',
                'posts_per_page' => -1
                );
            $loop = new WP_Query( $args );
            if ( $loop->have_posts() ) {
                while ( $loop->have_posts() ) : $loop->the_post();
                 $all_title = $product->name;
                    
                endwhile;
            } else {
                echo __( 'No products found' );
            }
            wp_reset_postdata();
        ?>
    </ul>



    <div class="form-group">
          <lable>Product Title</lable>
          <select>
          <option value="title" selected>Test</option>
          <option value="ms">Test 2</option>
          </select>
    </div>
1 Answers

Just updating your code a little to get all titles in the select dropdown at the end, as you wanted:

<php
global $product; ?>
    <ul class="products">
        <?php
            $products = wc_get_products(array(
                'limit'  => -1, // All products
                'status' => 'publish', // Only published products
            ) );
            $all_title = array();
            if ( $products ) {
                foreach ($products as $product){
                    $all_title[$product->get_slug()] = $product->get_title();
                }
            } else {
                echo __( 'No products found' );
            }
            wp_reset_postdata();
        ?>
    </ul>



    <div class="form-group">
          <lable>Product Title</lable>
          <select>
          <?php 
          foreach($all_title as $slug => $title){ 
            echo '<option value="'.$slug.'" selected>'.$title.'</option>';
          } ?>
          </select>
    </div>
Related