Query di tutti i post con un tag specifico
Ho bisogno di recuperare tutti i post con un tag specifico, ma sto ottenendo tutti i post invece. La mia query funziona se pubblico un post con il tag di cui ho bisogno ed elenco tutti i post con quel tag, ma quando pubblico un post con un altro tag, recupera anche il post appena pubblicato.
Questa è la mia query:
$original_query = $wp_query;
$wp_query = null;
$args=array(
'posts_per_page' => -1, // Recupera tutti i post
'tag' => $post_tag
);
$wp_query = new WP_Query( $args );
$post_titles=array();
$i=0;
if ( have_posts() ) :
while (have_posts()) : the_post();
$post_titles[$i]=get_the_ID() ;
$i++;
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();
È molto più semplice creare una nuova WP_Query che cercare di cancellare o sovrascrivere quella originale.
Se $post_tag è lo slug di un tag, potresti semplicemente usare:
<?php
$the_query = new WP_Query( 'tag='.$post_tag );
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// nessun post trovato
}
/* Ripristina i dati originali del Post */
wp_reset_postdata();
sì $post_tag è lo slug del tag ma non ho capito qual è la differenza fondamentale nel tuo codice scusa sono un principiante in wordpress
Antwan
La differenza principale è che il tuo codice cerca di annullare la Query principale di WP invece di crearne semplicemente una nuova.
Courtney Ivey
ottengo "nessun post trovato" mi dispiace ma c'è qualche differenza tra tag e tag slug?
Antwan
Nel tuo functions.php
/* Mostra Prodotti Correlati */
/* ======================== */
if ( ! function_exists( 'display_related_products' ) ) {
function display_related_products($post_tag) {
?>
<div class="related-products">
<!-- semplice WP_Query -->
<?php
$args = array(
'post_type' => 'product',
'tag' => $post_tag, // Qui viene filtrato in base al tag che desideri
'orderby' => 'id',
'order' => 'ASC'
);
$related_products = new WP_Query( $args );
?>
<?php while ( $related_products -> have_posts() ) : $related_products -> the_post(); ?>
<a href="<?php the_permalink(); ?>" class="related-product">
<?php if( has_post_thumbnail() ) : ?>
<?php the_post_thumbnail( 'full', array( 'class' => 'related-product-img', 'alt' => get_the_title() ) ); ?>
<?php endif; ?>
</a>
<?php endwhile; wp_reset_query(); ?>
</div>
<?php
}
}
Chiama da qualsiasi punto con
display_related_products('nome-del-tag');