P
P
Paul_Morte2019-02-05 16:19:34
WordPress
Paul_Morte, 2019-02-05 16:19:34

How to display a product card on the page in the right place using php code?

The question is of course very simple, but on the Internet, as usual, there is not what you need.
You need to display 1 product from a category or several products from a category in a specific location.
shortcode-sale.png
What is the best way to do this?
I found these options:
1) Shortcode for php

echo do_shortcode('[products tag="tag" columns="4"]');

Not suitable for future tasks. It will be necessary to display products from different categories one by one by tag.
2) WP_query query to the database
$args = array(
// Использование аргумента tax_query для установки параметров терминов таксономии
'tax_query' => array(
// Использование нескольких таксономий требует параметр relation
'relation' => 'AND', // значение AND для выборки товаров принадлежащим одновременно ко всем указанным терминам
// массив для категории
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => array( 16 ),
),
),
// Параметры отображения выведенных товаров
'posts_per_page' => 2, // количество выводимых товаров
'post_type' => 'product', // тип товара
'orderby' => 'date', // сортировка
);


$loop= new WP_Query($args);



  while ( $loop->have_posts() ): $loop->the_post(); ?>
  <div <?php post_class("inloop-product"); ?>>
    <div class="row">
      <div class="col-sm-4">
        <?php the_post_thumbnail("thumbnail-215x300"); ?>
      </div>
      <div class="col-sm-8">
        <h4>
          <a href="<?php the_permalink(); ?>">
            <?php the_title(); ?>
          </a>
        </h4>
        <?php the_content(); ?>
        <p class="price">
          <?php _e("Price:","examp"); ?>
          <?php woocommerce_template_loop_price(); ?>
        </p>
        <?php woocommerce_template_loop_add_to_cart(); ?>
      </div>
    </div>
  </div> 
  <?php endwhile; ?>

OK. But here a custom layout of the product card is used, which I would like to avoid and bring the entire display of the product to one view.
3) Hooks. It's the best. I'm looking for information on how to use the hook from archive-product.php, which just displays the products in the standard layout of the wokomers.
https://github.com/woocommerce/woocommerce/blob/ma...
As far as I figured out the hook + loop I needed:
woocommerce_product_loop_start();
wc_get_template_part( 'content', 'product' ); - вывод товара.
woocommerce_product_loop_end();

Here I would like to understand how to get products from the desired category (tag, attribute) using this code. How to pass product output parameters to a hook. Is this actually possible or not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Paul_Morte, 2019-02-08
@Paul_Morte

<?php 
$args = array(
// Использование аргумента tax_query для установки параметров терминов таксономии
'tax_query' => array(
// Использование нескольких таксономий требует параметр relation
'relation' => 'AND', // значение AND для выборки товаров принадлежащим одновременно ко всем указанным терминам
//!!!  Получаем массив продуктов из вукомерсарса
array(
'taxonomy' => 'product_cat', //  ищем в базе данных продукты из категории ...
'field' => 'id', 
'terms' => array( 16 ), // из категории с ID 16 (посмотреть в админке айдишник)
),
),
// Параметры отображения выведенных товаров
'posts_per_page' => 3, // количество выводимых товаров
'post_type' => 'product', // тип товара
'orderby' => 'date', // сортировка
);

$product = new WP_Query($args);


//Тут подключаем обертку <ul> вызывая хук вукомерса
  woocommerce_product_loop_start();
  do_action( 'woocommerce_shop_loop' ); 


// Мы получили в $product массив товаров (продуктов) и теперь выводим каждый в обертке вукомерса
  while ( $product->have_posts() ): $product->the_post(); ?>
  
  
  
  <?php  
    
 // если переменная существует 
if ( empty( $product ) ) {
  return;
}
?>

//  post_class();  - подключаем классы css для отображения товара
<li <?php post_class();  ?>>
  <?php
  /**
   * Hook: woocommerce_before_shop_loop_item.
   *
   * @hooked woocommerce_template_loop_product_link_open - 10
   */
  do_action( 'woocommerce_before_shop_loop_item' );
  /**
   * Hook: woocommerce_before_shop_loop_item_title.
   *
   * @hooked woocommerce_show_product_loop_sale_flash - 10
   * @hooked woocommerce_template_loop_product_thumbnail - 10
   */
  do_action( 'woocommerce_before_shop_loop_item_title' );
  /**
   * Hook: woocommerce_shop_loop_item_title.
   *
   * @hooked woocommerce_template_loop_product_title - 10
   */
  do_action( 'woocommerce_shop_loop_item_title' );
  /**
   * Hook: woocommerce_after_shop_loop_item_title.
   *
   * @hooked woocommerce_template_loop_rating - 5
   * @hooked woocommerce_template_loop_price - 10
   */
  do_action( 'woocommerce_after_shop_loop_item_title' );
  /**
   * Hook: woocommerce_after_shop_loop_item.
   *
   * @hooked woocommerce_template_loop_product_link_close - 5
   * @hooked woocommerce_template_loop_add_to_cart - 10
   */
  do_action( 'woocommerce_after_shop_loop_item' );
  
  

  

  
  ?>
  
</li>
  
  
  
  <?php endwhile; ?>
  


  <?php 
  woocommerce_product_loop_end();


  ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question