首页 > 解决方案 > 如何与下一个转到其他帖子,但保持在同一类别中。我使用投资组合插件 wordpress

问题描述

这是我尝试过的,但它不起作用,它没有显示任何内容

<?php 

    next_post_link( '%link', '%title', TRUE ); 

    previous_post_link( '%link', '%title', TRUE ); 
?>

这有效,但不按类别排序

<?php

   next_post_link(); 
   previous_post_link(); 
?>

我使用摄影主题 wordpress:https ://themeforest.net/item/photography-responsive-photography-theme/13304399

标签: phpwordpressportfolio

解决方案


global $post;

$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
}

推荐阅读