Roots/Sage主题Projects自定义文章同父分类上下篇链接实现问题
方案1:使用WordPress原生函数调整(最简实现)
你之前调用previous_post_link和next_post_link时未指定自定义分类法,第三个参数TRUE默认仅适配系统默认的category分类法,因此会无输出。调整参数即可适配你的projects_category分类法:
<?php // 第三个参数为true表示限定同分类,第四个参数指定排除的分类ID,第五个参数指定自定义分类法名称 previous_post_link( '%link', '上一个项目', true, '', 'projects_category' ); next_post_link( '%link', '下一个项目', true, '', 'projects_category' ); ?>
如果需要限定为仅当前文章所属的一级父分类下的所有文章(包含子分类文章),可以在主题的functions.php中添加如下钩子过滤:
add_filter( 'get_previous_post_where', 'filter_adjacent_post_by_parent_category', 10, 5 ); add_filter( 'get_next_post_where', 'filter_adjacent_post_by_parent_category', 10, 5 ); function filter_adjacent_post_by_parent_category( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) { // 仅对projects自定义文章类型生效 if ( $post->post_type !== 'projects' || $taxonomy !== 'projects_category' ) return $where; // 获取当前文章所属的所有分类 $terms = wp_get_post_terms( $post->ID, 'projects_category' ); if ( empty( $terms ) ) return $where; // 取第一个分类的顶级父分类ID $parent_term = $terms[0]; while ( $parent_term->parent != 0 ) { $parent_term = get_term( $parent_term->parent, 'projects_category' ); } // 筛选所有属于该父分类(含子分类)的文章 $where .= " AND p.ID IN ( SELECT object_id FROM {$GLOBALS['wpdb']->term_relationships} WHERE term_taxonomy_id IN ( SELECT term_taxonomy_id FROM {$GLOBALS['wpdb']->term_taxonomy} WHERE taxonomy = 'projects_category' AND ( term_id = {$parent_term->term_id} OR parent = {$parent_term->term_id} ) ) )"; return $where; }
方案2:按你梳理的逻辑实现(自定义遍历)
直接在content.single-projects.php中添加如下代码即可:
<?php $current_id = get_the_ID(); // 1. 获取当前文章所属的顶级父分类 $terms = wp_get_post_terms( $current_id, 'projects_category' ); if ( !empty( $terms ) ) { $parent_term = $terms[0]; while ( $parent_term->parent != 0 ) { $parent_term = get_term( $parent_term->parent, 'projects_category' ); } // 2. 查询该父分类下所有projects文章,按发布时间排序 $args = [ 'post_type' => 'projects', 'posts_per_page' => -1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'tax_query' => [ [ 'taxonomy' => 'projects_category', 'field' => 'term_id', 'terms' => $parent_term->term_id, 'include_children' => true // 不需要包含子分类文章的话设为false ] ] ]; $projects = get_posts( $args ); $ids = wp_list_pluck( $projects, 'ID' ); $current_index = array_search( $current_id, $ids ); // 3. 输出上下篇链接 if ( isset( $ids[$current_index - 1] ) ) { echo '<a href="' . get_permalink( $ids[$current_index - 1] ) . '">上一个项目</a>'; } if ( isset( $ids[$current_index + 1] ) ) { echo '<a href="' . get_permalink( $ids[$current_index + 1] ) . '">下一个项目</a>'; } } ?>
如果项目文章数量较多,建议优先使用方案1,数据库查询性能更高
内容的提问来源于stack exchange,提问作者Dealion
相关产品推荐
相关产品推荐

