web-dev-qa-db-fra.com

Afficher les messages de la même catégorie en utilisant le lien message suivant/précédent

J'utilise ce code, mais une fois que je clique sur le lien post suivant/post précédent, je suis redirigé vers le post suivant/post précédent d'une autre catégorie.

 previous_post_link( '%link', 'Prev post in category', $in_same_term = true );
 next_post_link( '%link', 'Next post in category', $in_same_term = true );

J'essaie de résoudre mon problème en utilisant cet article .

Voici le code que j'utilise pour les publications et les catégories, et je n'utilise pas les types et les catégories de publication personnalisés:

$post_id = $post->ID;
$cat = get_the_category();
$current_cat_id = $cat[0]->cat_ID;
$args = array( 
    'category' => $current_cat_id, 
    'orderby'  => 'post_date', 
    'order'    => 'DESC' 
);
$posts = get_posts( $args );
foreach( $posts as $post ) {
    echo $post->post_content;
}
previous_post_link( '%link', 'Prev post in category', $in_same_term = true );
next_post_link( '%link', 'Next post in category', $in_same_term = true );

Il s'agit essentiellement de récupérer tous les articles en fonction de la catégorie, et je souhaite maintenant que le lien article suivant/article précédent ne fonctionne que pour cette catégorie.

7
user54318

Voici le code pour obtenir les liens précédents et suivants par catégorie sur les publications:

<?php
$post_id = $post->ID; // current post ID
$cat = get_the_category(); 
$current_cat_id = $cat[0]->cat_ID; // current category ID 

$args = array( 
    'category' => $current_cat_id,
    'orderby'  => 'post_date',
    'order'    => 'DESC'
);
$posts = get_posts( $args );
// get IDs of posts retrieved from get_posts
$ids = array();
foreach ( $posts as $thepost ) {
    $ids[] = $thepost->ID;
}
// get and echo previous and next post in the same category
$thisindex = array_search( $post_id, $ids );
$previd    = isset( $ids[ $thisindex - 1 ] ) ? $ids[ $thisindex - 1 ] : 0;
$nextid    = isset( $ids[ $thisindex + 1 ] ) ? $ids[ $thisindex + 1 ] : 0;

if ( $previd ) {
    ?><a rel="prev" href="<?php echo get_permalink($previd) ?>">Previous</a><?php
}
if ( $nextid ) {
    ?><a rel="next" href="<?php echo get_permalink($nextid) ?>">Next</a><?php
}
16
user54318

Les fonctions previous_post_link et next_post_link ont toutes deux cinq paramètres: $format: Chaîne de formatage du lien, utilisée pour contrôler ce qui vient avant et après le lien.
$link: Lien texte à afficher
$in_same_term: Indique si le message suivant/précédent doit figurer dans le même terme de taxonomie que le message actuel
$excluded_terms: termes à exclure des publications $taxonomy: taxonomie à utiliser lorsque $in_same_term est défini sur true. Comme vous pouvez le constater, le paramètre $in_same_term correspond exactement à vos besoins. Cependant, vous ne l'utilisez pas correctement dans votre exemple de code. En fait, vous transmettez le résultat de l'attribution de true à une variable $in_same_term. Cela ne fonctionnera pas: passer un argument est aussi simple que de passer une valeur:

previous_post_link( '%link', 'Prev post in category', true );
next_post_link( '%link', 'Next post in category', true );

Edit: (édité après que OP ait mis à jour sa question) Le problème est que previous_post_link et next_post_link utilisent l'objet de publication global, que vous écrasez. Pour éviter cela, utilisez un autre nom de variable dans votre boucle $posts-, tel que $singlepost:

foreach ( $posts as $singlepost ) {
    echo $singlepost->post_content
}

De cette façon, l'objet $post global est préservé. Vous pouvez également stocker l'objet de publication global dans une variable temporaire et réinitialiser $post ultérieurement, mais cela n'est vraiment nécessaire que si vous appelez setup_postdata (ce que vous n'êtes pas).

3
engelen

Votre code n'a pas de sens pour moi, mis à part une erreur de syntaxe. En l'état actuel de votre code, lorsque vous cliquez sur un message d'une page de message/blog, vous accédez à la vue unique du message comme il se doit. Seul ce post est affiché sur single.php.

Le problème commence lorsque vous cliquez sur les liens de publication, qu’il s’agisse du lien de publication précédent ou suivant. Ce qui est retourné, ce sont toutes les publications de cette catégorie lorsque la page suivante/précédente est chargée. C'est ainsi que vous avez codé votre single.php, et pourquoi vos liens de publication ne fonctionnent pas comme vous le souhaitiez.

Je n'utiliserais pas get_posts() pour configurer ma boucle sur la page single.php. Je voudrais juste utiliser la boucle appropriée normale. Veuillez consulter cette page du codex sur Développement du thème

Voici un exemple de single.php qui fonctionnera comme prévu

<?php
get_header(); ?>

<div id="main-content" class="main-content">

    <div id="primary" class="content-area">
        <div id="content" class="site-content" role="main">
            <?php
                // Start the Loop.
                while ( have_posts() ) : the_post(); ?>

            <?php
                    get_template_part( 'content', get_post_format() );

                    // Previous/next post navigation.
                    previous_post_link( '%link', 'Prev post in category', true );
                    next_post_link( '%link', 'Next post in category', true );

                    // If comments are open or we have at least one comment, load up the comment template.
                    if ( comments_open() || get_comments_number() ) {
                        comments_template();
                    }
                endwhile;
            ?>
        </div><!-- #content -->
    </div><!-- #primary -->

<?php get_sidebar( 'content' ); ?>
</div><!-- #main-content -->

<?php
get_footer();

Comme indiqué dans l'autre réponse, allez lire comment utiliser le next_post_link et le previous_post_link

1
Pieter Goosen

J'ai eu le même problème, mais j'avais besoin de tout cela pour le type d'article personnalisé et la taxonomie personnalisée. user54318 m'a dirigé dans la bonne direction, ce qui n'est pas capable d'exécuter cpt, je vais donc partager mes résultats ici aussi:

//get custom taxonomies.
$terms = wp_get_post_terms( get_the_ID(), 'product_cat' ); //last argument is the custom taxonomy. change to desired tax
//run through all terms and filter out the one, that i need. 
$stay_in = array();
foreach( $terms as $term ) :
/*this loop looks for a category, that is a children of category id 37. change to your needs. 
only importance is to build an array of term ids, to be included in the previous/next behaviour, so if you already know your ids, you could also use something like $stay_in = array( 43 ); and skip this whole loop..*/
    if ( $term->parent == 37 ) :
        $stay_in[] = $term->term_id;
        break; //break out the foreach, if found.
    endif;
endforeach;
//get all post ids, that are in my defined category
$args = array(
    'post_type'         => 'product', //custom post type
    'posts_per_page'    => -1,
    'tax_query'         => array(
        array(
            'taxonomy'  => 'product_cat', // custom taxonomy
            'field'     => 'term_id',
            'terms'     => $stay_in,
            'operator'  => 'IN', //change to your needs.. IN, NOT IN, AND, EXISTS, NOT EXISTS
        )
    ),
    'orderby'           => 'post_date',
    'order'             => 'ASC',
    'fields'            => 'ids', //only return the post ids, not the whole post-objects
);
$all_posts = new WP_Query( $args );
//search for the current post by its id and look for the previous / next ids
$this_index = array_search( $post->ID, $all_posts->posts );
$prev_id = $all_posts->posts[ $this_index - 1 ];
$next_id = $all_posts->posts[ $this_index + 1 ];
//echo links, if prevoius/next exists
if ( ! empty( $prev_id ) ) :
    echo '<a rel="prev" href="' . get_permalink( $prev_id ) . '">' . __( 'previous', 'your_theme_text_domain' ) . '</a>';
endif;

if ( ! empty( $next_id ) ) :
    echo '<a rel="next" href="' . get_permalink( $next_id ) . '">' . __( 'next', 'your_theme_text_domain' ) . '</a>';
endif;
wp_reset_postdata();
0
honk31