【问题标题】:Display the posts from the same category when user clicks on next/previous post in single.php page当用户单击 single.php 页面中的下一个/上一个帖子时,显示来自同一类别的帖子
【发布时间】:2014-10-24 02:31:12
【问题描述】:

我正在使用此代码,但一旦我点击下一篇文章/上一篇文章链接,我将被重定向到不同类别的下一篇文章/上一篇文章

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

我正在尝试使用这篇文章来解决我的问题http://codex.wordpress.org/Function_Reference/next_post_link

谢谢

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    这是获取帖子上基于类别的上一个和下一个链接的代码

    $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 = $ids[$thisindex-1];
    $nextid = $ids[$thisindex+1];
    
    if (!empty($previd)){
    ?>
    <a rel="prev" href="<?php echo get_permalink($previd) ?>">Previous</a>
    <?php
    }
    if (!empty($nextid)){
    ?>
    <a rel="next" href="<?php echo get_permalink($nextid) ?>">Next</a>
    <?php
    }
    ?>
    

    【讨论】:

      【解决方案2】:

      你可以这样做...

      只需将参数 $in_same_term 更改为 true..

      previous_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' );
      

      【讨论】:

      • 好吧..即使我也做了同样的 $in_same_term = true。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多