Search code examples
woocommerce-theming

Woocommerce - could someone give me please a real world example with "WC_Product_Query" in a loop like WP_Query


i'm developing a custom Woocommerce theme, i want to use "WC_Product_Query" with html tag like the example below, in a custom loop, to show custom woocommerce layout product in home page, seems like i tested it. it doesn't work. Since i don't master it, i'd like to see how it should be in action with HTML, because they say to not use the "WP_Query", it could break in future update of Woocommerce. Any help would be appreciated.

 <?php


      $args = array(
        'post_type' => 'agenda',
        'posts_per_page' => 2,
        'orderby' => 'meta_value_num',
        'order' => 'ASC',

      );

      $agenda = new WP_Query($args);


      while ($agenda->have_posts()) {
        $agenda->the_post(); ?>

        <div class="wapper_agenda">
        <h3><?php the_title();?>
       </div>
    <?php  }
    ?>


Solution

  • few days ago, i was asking how to make a custom loop with woocommerce to design the way i want a product to output in the front-end of the site or anywhere in the theme, without "WP_Query". After some search and practice, i found i could do this with "wc_get_products" in a foreach loop like the code below, you can output anything, just print the variable var_dump($products), and check the woocommerce documentation: https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query

    <section class="container-fluid container_product_home">
      <div class="container">
        <?php
    
        // get the category Luxury
        $args = array(
            'post_type' => 'product',
            'category' => array( 'luxury')
    
        );
        $products = wc_get_products( $args );
        if ($products) {?>
          <?php
        foreach ($products as $prod) { ?>
          <div class="row">
            <div class="col-sm-6">
    
                  <?php
                    $val_img = $prod->image_id;
                  echo  wp_get_attachment_image( $val_img, 'full', ["class" => "img-fluid"]); ?>
    
    
            </div>
            <div class="col-sm-6">
              <div class="second_col_prod">
    
    
                <div class="product_home" style="padding-top:10px;">
                      <p><?php  echo $prod->description;?></p>
                </div>
    
    			<div class="btn_product">
    				
                <a class="btn bnt default btn-primary btn-block btn_prod"href="<?php echo get_permalink( $prod->post->ID ) ?>">EXPLORE THIS </a>
    			</div>
    
              </div>
            </div>
          </div>
        <?php }
    
          ?>
        <?php }
    
    
        ?>
      </div>
      </section>