Visualizzare prodotti in evidenza tramite loop personalizzato in WooCommerce su template page

24 lug 2015, 00:51:58
Visualizzazioni: 94.1K
Voti: 24

Vorrei visualizzare 6 prodotti in evidenza del mio negozio Woocommerce nel template home-page.php. Dopo alcune ricerche ho scoperto che il modo corretto per farlo è attraverso un loop personalizzato (non voglio usare shortcode perché vorrei aggiungere classi aggiuntive per lo stile ecc.). Ho anche scoperto che la chiave che WooCommerce utilizza per i prodotti in evidenza è '_featured'. Ho assemblato il codice qui sotto per visualizzare i prodotti che ho scelto come prodotti in evidenza nel mio negozio, ma non funziona... Ogni aiuto è apprezzato.

<?php
    // Argomenti per la query dei prodotti in evidenza
    $args = array(
        'post_type'   => 'product',
        'stock'       => 1,
        'showposts'   => 6,
        'orderby'     => 'date',
        'order'       => 'DESC',
        'meta_query'  => array(
            array(
                'key'     => '_featured',
                'value'   => 0,
                'compare' => '>',
                'type'    => 'numeric'
            )
        )
    );

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

        <li>    
            <?php 
                if ( has_post_thumbnail( $loop->post->ID ) ) 
                    echo get_the_post_thumbnail( $loop->post->ID, 'shop_catalog' ); 
                else 
                    echo '<img src="' . woocommerce_placeholder_img_src() . '" alt="Placeholder" width="65px" height="115px" />'; 
            ?>
            <h3><?php the_title(); ?></h3>

            <?php 
                echo $product->get_price_html(); 
                woocommerce_template_loop_add_to_cart( $loop->post, $product );
            ?>    
        </li>

<?php 
    endwhile;
    wp_reset_query(); 
?>
1
Commenti

Aggiungi il risultato da var_dump( get_meta_values( '_featured', 'product' ); dove la funzione get_meta_values è supportata dalla funzione personalizzata spiegata in questa risposta

Pieter Goosen Pieter Goosen
24 lug 2015 07:34:48
Tutte le risposte alla domanda 10
2
25

Ciò è cambiato in WooCommerce 3.0. Non si tratta più semplicemente di una meta_query, ma ora include anche una tax_query. Gli argomenti ora sono:

    $meta_query  = WC()->query->get_meta_query();
    $tax_query   = WC()->query->get_tax_query();
    $tax_query[] = array(
        'taxonomy' => 'product_visibility',
        'field'    => 'name',
        'terms'    => 'featured',
        'operator' => 'IN',
    );

    $args = array(
        'post_type'           => 'product',
        'post_status'         => 'publish',
        'ignore_sticky_posts' => 1,
        'posts_per_page'      => $atts['per_page'],
        'orderby'             => $atts['orderby'],
        'order'               => $atts['order'],
        'meta_query'          => $meta_query,
        'tax_query'           => $tax_query,
    );

Vedi woocommerce/includes/class-wc-shortcodes.php

8 mag 2017 17:27:17
Commenti

Esattamente quello che stavo cercando!

joshkrz joshkrz
11 mag 2018 01:09:17

Anche per Woocommerce 3.0, raccomandano di usare wc_placeholder_img_src invece di woocommerce_placeholder_img_src.

Robotnicka Robotnicka
25 mag 2018 03:46:17
2
18

Modifica i tuoi argomenti in questo modo:

$meta_query   = WC()->query->get_meta_query();
$meta_query[] = array(
    'key'   => '_featured',
    'value' => 'yes'
);
$args = array(
    'post_type'   =>  'product',
    'stock'       =>  1,
    'showposts'   =>  6,
    'orderby'     =>  'date',
    'order'       =>  'DESC',
    'meta_query'  =>  $meta_query
);

Se vai in wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) puoi vedere come è implementato per gli shortcode di WC.

15 set 2015 13:52:35
Commenti

È importante notare che '_featured' non viene memorizzato come valore numerico. Viene memorizzato come stringa 'yes' o 'no'. Tutto il resto nella domanda dell'OP dovrebbe funzionare, ha funzionato per me.

i_a i_a
3 lug 2016 20:02:55

A partire da WooCommerce 3.0, questa soluzione non funziona più. Si prega di vedere la mia risposta aggiornata qui sotto.

dpruth dpruth
12 giu 2018 22:02:29
0

Loop dei Prodotti in Evidenza in WooCommerce 3

<ul class="products">
<?php
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 12,
    'tax_query' => array(
            array(
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'    => 'featured',
            ),
        ),
    );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
} else {
    echo __( 'Nessun prodotto trovato' );
}
wp_reset_postdata();
?>
24 dic 2017 09:59:23
3

Secondo il Wiki di WooCommerce:

Creare WP_Queries personalizzati o query al database [per recuperare prodotti] potrebbe causare problemi al tuo codice nelle versioni future di WooCommerce poiché i dati si stanno spostando verso tabelle personalizzate per una migliore performance.

WooCommerce raccomanda di utilizzare wc_get_products() o WC_Product_Query() invece di WP_Query() o get_posts().

Ho scritto un articolo con il codice che ho utilizzato per ottenere ciò che desideri qui: https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/

24 mag 2018 21:58:39
Commenti

scusa, senza vedere del codice scritto, è difficile capire il tuo articolo. Potresti per favore includere del codice?

HOY HOY
5 giu 2019 17:59:30

@HOY il plugin di embed era rotto; ora è stato sistemato e puoi vedere il codice!

cfx cfx
5 giu 2019 23:07:32

grazie, mentre cercavo soluzioni, ho trovato questa qui sotto. Non sono sicuro di come differisca dalla tua dato che non ho potuto controllare la tua approfonditamente, ma è molto breve e mi ha aiutato con un loop di prodotti personalizzato. https://www.kathyisawesome.com/woocommerce-modifying-product-query/

HOY HOY
5 giu 2019 23:28:38
0

So che questo è abbastanza vecchio, ma ho appena condiviso una soluzione alternativa qui e penso che possa aiutare anche chi arriva a questo argomento.

Invece di usare meta_query o tax_query, puoi usare anche wc_get_featured_product_ids():

$args = array(
    'post_type'           => 'product',
    'posts_per_page'      => 6,
    'orderby'             => 'date',
    'order'               => 'DESC',
    'post__in'            => wc_get_featured_product_ids(),
);

$query = new WP_Query( $args );

Spero sia utile!

29 apr 2018 01:14:51
0

Basato su: https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query

Proverei:

fuori dal loop:

$args = array (
'limit' => 6,
'orderby' => 'title',
'order' => 'ASC',
'category' => $club_cat,
'stock_status' => 'instock',
'featured' => true,

 );

 $products = wc_get_products( $args );

nel loop:

$query = new WC_Product_Query( array(
'limit' => 6,
'orderby' => 'title',
'order' => 'ASC',
'category' => $club_cat,
'stock_status' => 'instock',
'featured' => true,
'return' => 'ids',

 ) );

 $products = $query->get_products();
26 set 2018 15:09:39
0

Le persone dovrebbero iniziare a utilizzare wc_get_products perché WooCommerce ha dichiarato che questo è il metodo standard per recuperare i prodotti. wc_get_products ha un argomento "featured" che deve essere semplicemente impostato su true. Quindi il codice è semplicemente il seguente.

<?php 

// Mostra i prodotti in evidenza per categoria. In questo caso è "shirts" che è lo slug della categoria.
$query_args = array(
    'featured' => true,  
    'category' => array( 'shirts' ),
);
$products = wc_get_products( $query_args );

global $post;
$columns = wc_get_loop_prop( 'columns' );
?>
<div class="woocommerce columns-<?php echo esc_attr( $columns ); ?>">
  <?php
    woocommerce_product_loop_start();
    foreach ($products as $product) {
        $post = get_post($product->get_id());
        setup_postdata($post);
        wc_get_template_part('content', 'product');
    }
    wp_reset_postdata();
    woocommerce_product_loop_end();
  ?>
</div>

Vedi il post completo qui: https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/

12 lug 2020 15:35:24
0

se dai un'occhiata al database nella tabella wp_postmeta vedrai che meta_key sarà _featured e meta_value sarà yes o no, quindi invece del valore 0 o 1 scrivi yes o no

<?php
    $q = new WP_Query([
      'post_type'   =>  'product', // Tipo di post: prodotto
      'stock'       =>  1,        // Solo prodotti in stock
      'showposts'   =>  3,        // Mostra 3 prodotti
      'orderby'     =>  'date',   // Ordina per data
      'order'       =>  'DESC',   // Ordine decrescente
      'meta_query'  =>  [ 
        ['key' => '_featured', 'value' => 'yes' ] // Solo prodotti in evidenza
        ]
    ]);
    if ( $q->have_posts() ) :
        while ( $q->have_posts() ) : $q->the_post();
            // visualizza le informazioni del prodotto
        endwhile; wp_reset_query();
    endif;
?>
11 lug 2016 23:02:39
1
<ul class="products">
    <?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12,
            'tax_query' => array(
                    array(
                        'taxonomy' => 'product_visibility',
                        'field'    => 'name',
                        'terms'    => 'featured',
                    ),
                ),
            );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
               echo '<p>'.get_the_title().'</p>';
            endwhile;
        } else {
            echo __( 'Nessun prodotto trovato' );
        }
        wp_reset_postdata();
    ?>
</ul><!--/.products-->
3 apr 2019 15:37:13
Commenti

Per favore [modifica] la tua risposta e aggiungi una spiegazione: perché potrebbe risolvere il problema?

fuxia fuxia
3 apr 2019 17:40:12
0

Aggiornamento per il 2021 - Dovresti usare wc_get_products()

Inoltre, l'esempio di codice di Jameshwart (sopra) non ha funzionato per me, ecco come ho impostato i postdata e ho usato wc_get_template. Testato e funzionante.

$args = array(
    'status' => 'publish',
    'limit' => 20,
    'paginate' => true, //deve essere true per ottenere ->total
    'return' => 'ids',
);
$products = wc_get_products( $args );

if ($products->total >= 1):

    woocommerce_product_loop_start();

    foreach($products->products as $pid):

        do_action( 'woocommerce_shop_loop' );

        $product = get_post($pid);
        setup_postdata($GLOBALS['post'] =& $product);
        wc_get_template_part('content', 'product');

    endforeach;
    wp_reset_postdata();

    woocommerce_product_loop_end();


endif; //abbiamo prodotti
4 ago 2021 17:55:03