Come visualizzare gli articoli correlati della stessa categoria?

2 ott 2011, 17:08:14
Visualizzazioni: 55.2K
Voti: 17

È possibile visualizzare gli articoli correlati della stessa categoria dell'articolo corrente?

0
Tutte le risposte alla domanda 4
4
32

Una possibilità:

$related = get_posts( 
    array( 
        'category__in' => wp_get_post_categories( $post->ID ), 
        'numberposts'  => 5, 
        'post__not_in' => array( $post->ID ) 
    ) 
);

if( $related ) { 
    foreach( $related as $post ) {
        setup_postdata($post);
        /*qualunque cosa tu voglia mostrare in output*/
    }
    wp_reset_postdata();
}

Riferimenti:

Risposta riscritta basata su WP_Query():

$related = new WP_Query(
    array(
        'category__in'   => wp_get_post_categories( $post->ID ),
        'posts_per_page' => 5,
        'post__not_in'   => array( $post->ID )
    )
);

if( $related->have_posts() ) { 
    while( $related->have_posts() ) { 
        $related->the_post(); 
        /*qualunque cosa tu voglia mostrare in output*/
    }
    wp_reset_postdata();
}
2 ott 2011 18:07:14
Commenti

Fai molta attenzione ai nomi delle tue variabili! Stai usando una variabile globale $post per eseguire la tua query, per poi ridefinire $post nello stesso contesto all'interno del tuo ciclo foreach.

EAMann EAMann
2 ott 2011 19:15:21

@EAMann - in linea generale hai ragione - però nella mia esperienza, usando setup_postdata() con qualsiasi cosa diversa da $post non restituisce l'output corretto per the_title() ad esempio. wp_reset_postdata() in teoria dovrebbe occuparsi di resettare $post.

Michael Michael
2 ott 2011 20:08:25

Questo perché setup_postdata() stesso fa riferimento a $post come variabile globale. Invece di usare get_posts() dovresti definire un'istanza personalizzata di WP_Query e usarla per ottenere i tuoi post. Configurerà i dati del post per te e farà funzionare the_title() e altri nel modo in cui dovrebbero.

EAMann EAMann
3 ott 2011 04:12:12

@EAMann Questo è un post piuttosto vecchio, ma sarebbe apprezzato se potessi scrivere una risposta su come farlo correttamente con la query personalizzata e tutto il resto

GiantCowFilms GiantCowFilms
25 nov 2015 17:47:47
1

Ecco un'altra opzione pulita e molto flessibile:

Inserisci questo codice nel tuo file functions.php

function example_cats_related_post() {

    $post_id = get_the_ID();
    $cat_ids = array();
    $categories = get_the_category( $post_id );

    if(!empty($categories) && is_wp_error($categories)):
        foreach ($categories as $category):
            array_push($cat_ids, $category->term_id);
        endforeach;
    endif;

    $current_post_type = get_post_type($post_id);
    $query_args = array( 

        'category__in'   => $cat_ids,
        'post_type'      => $current_post_type,
        'post__not_in'    => array($post_id),
        'posts_per_page'  => '3'


     );

    $related_cats_post = new WP_Query( $query_args );

    if($related_cats_post->have_posts()):
         while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
            <ul>
                <li>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                    <?php the_content(); ?>
                </li>
            </ul>
        <?php endwhile;

        // Ripristina i dati originali del Post
        wp_reset_postdata();
     endif;

}

Ora puoi semplicemente chiamare la funzione ovunque nel tuo sito usando:

<?php example_cats_related_post() ?>

Potresti voler rimuovere gli elementi della lista o stilizzarli secondo le tue esigenze.

*Modifica - devi cambiare questo: post_not_in in questo post__not_in nella tua query

2 lug 2018 14:58:51
Commenti

Mostra solo un post. È possibile mostrare tutti i post della stessa categoria in una pagina di categoria?

Rahul Rahul
29 ago 2019 09:08:15
0

puoi usare questo codice per ottenere articoli correlati dalla stessa categoria

$args = array(
                'category__in' => wp_get_post_categories( get_queried_object_id() ),
                'posts_per_page' => 5,
                'orderby'       => 'rand',
                'post__not_in' => array( get_queried_object_id() )
                );
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) : ?>

        <ul class="">
        <!-- the loop -->
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

            <li>
                <h6>
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                    </a>
                </h6>
            </li>

        <?php endwhile; ?>
        <!-- end of the loop -->
        </ul>

        <?php wp_reset_postdata(); ?>

     <?php endif; ?>

e usa questo codice per ottenere articoli correlati dagli stessi tag

$tags = wp_get_post_terms( get_queried_object_id(), 'post_tag', ['fields' => 'ids'] );
    $args = [
        'post__not_in'        => array( get_queried_object_id() ),
        'posts_per_page'      => 5,
        'orderby'             => 'rand',
        'tax_query' => [
            [
                'taxonomy' => 'post_tag',
                'terms'    => $tags
            ]
        ]
    ];
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) : ?>

        <ul class="">
        <!-- the loop -->
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

            <li>
                <h6>
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                    </a>
                </h6>
            </li>

        <?php endwhile; ?>
        <!-- end of the loop -->
        </ul>

        <?php wp_reset_postdata(); ?>

    <?php endif; ?>
2 dic 2019 18:05:36
0

Questa risposta garantisce che i post correlati siano ordinati in base al numero di tag corrispondenti.

Ad esempio, se un articolo ha 3 tag e c'è un altro articolo che ha esattamente gli stessi 3 tag, dovrebbe apparire in cima alla lista. L'ordinamento secondario dovrebbe essere per data del post in modo che i contenuti più recenti siano favoriti.

/**
 * Seleziona contenuti con tag in comune.
 * Ordina in modo che i contenuti con più tag corrispondenti siano in cima.
 * Ordinamento secondario sui contenuti più recenti per primi.
 *
 * @param $post_id
 * @param int $limit
 * @return array
 */
function related_posts($post_id, $limit = 5) {

    global $wpdb;

    $query  = "SELECT TOP %d x.object_id as ID
FROM (
SELECT TOP 10 tr1.object_id, COUNT(tr1.term_taxonomy_id) AS common_tag_count
FROM {$wpdb->term_relationships} AS tr1
INNER JOIN {$wpdb->term_relationships} AS tr2 ON tr1.term_taxonomy_id = tr2.term_taxonomy_id
WHERE tr2.object_id = %d
GROUP BY tr1.object_id
HAVING tr1.object_id != %d
ORDER BY COUNT(tr1.term_taxonomy_id) DESC
) x
INNER JOIN {$wpdb->posts} p ON p.ID = x.object_id
ORDER BY common_tag_count DESC, p.post_date DESC;";

    $query = $wpdb->prepare($query, $limit, $post_id, $post_id);
    $ids = $wpdb->get_col($query);
    $posts = [];
    foreach($ids as $id)  {
        $posts[] = get_post($id);
    }

    return $posts;

}

La query interna qui serve per selezionare i contenuti con il maggior numero di tag corrispondenti, mentre la query esterna viene utilizzata solo per applicare l'ordinamento secondario per data del post.

Nota: questa query è scritta per SQL Server, quindi potrebbe essere necessario aggiornare la sintassi (ad esempio TOP vs LIMIT).

20 ago 2018 17:59:38