首页 > 解决方案 > 从存档调用的 CPT 页面上的 Wordpress 上一个和下一个链接

问题描述

我有一个 CPT 和 3 个自定义分类法。对于每个分类,都存在存档页面,其中包含按标题排序的分类术语的项目。

项目页面的页脚中有 prevoius/next-Links,但这些链接到发布日期此 CPT 的上一个/下一个项目。

正如访问者所期望的那样,我如何将其替换为存档中上一个/下一个项目的链接?

第一个想法是从存档页面传输循环内容并查找相邻项目?

标签: wordpressarchive

解决方案


您需要将此代码添加到您的单一 myposttype。

/* Fist get the posts from specific taxonomy */
$postByTaxonomy = get_posts(array(
  'post_type' => 'post', // fruit
  'numberposts' => -1,
  //'order'          => 'ASC', // you can add to order by name
  //'orderby'        => 'title', // you can add to order by name
  'tax_query' => array(
    array(
      'taxonomy' => 'fruit-category', // category of Fruit CPT
      'field' => 'slug',
      'terms' => 'fruit-category-1', // This is the one you check from editor page
    )
  )
)); 

/* Store the IDs in array from get_posts above */
$theIDs = array();
foreach ($postByTaxonomy as $pbt) {
  $theIDs[] += $pbt->ID;
}
/* print_r($theIDs) = Array ( [0] => 3696 [1] => 3697 [2] => 128 [3] => 4515 [4] => 4516 [5] => 4514 ) */


/* Now we will use a php function array_search() for us to get the current post and we can set the previous and next IDs */
$current = array_search( get_the_ID(), $theIDs); /* here you need to get the id of the post get_the_ID() or $post->ID */
$prevID = $theIDs[$current-1];
$nextID = $theIDs[$current+1];

/* DISPLAY - Now that we have the IDs of the prev/next post you can use them to your template in your case the permalink */
<a href="<?php echo get_permalink($prevID); ?>"> Previous</a>
<a href="<?php echo get_permalink($nextID); ?>"> Next</a>

推荐阅读