是否有任何WP内置功能可以完成正确的工作?
不
[我]必须为此编写自定义查询吗?
编号使用get_terms(). 这里有一个例子。
添加wpse_99513_adjacent_category
类的函数。php主题文件,并按如下方式调用:
$category_ids = new wpse_99513_adjacent_category( \'category\', \'id\', false );
--“category”是分类法,“id”是数据库查询的排序依据字段,false显示空类别
要获取下一个分类,请使用以下内容:
$next_category = $category_ids->next( $category );
--$category是您正在检查的类别的id,
--$next\\u category如果有错误,则设置为false,否则设置为next id。
以前的作品也是这样:
$previous_category = $category_ids->previous( $category );
--$category是您要检查的类别的id,
--$previous\\u category如果有错误,则设置为false,否则设置为previous id。
对于跳过空类别的Slug,请使用:
$category_ids = new wpse_99513_adjacent_category( \'category\', \'slug\' );
class wpse_99513_adjacent_category {
public $sorted_taxonomies;
/**
* @param string Taxonomy name. Defaults to \'category\'.
* @param string Sort key. Defaults to \'id\'.
* @param boolean Whether to show empty (no posts) taxonomies.
*/
public function __construct( $taxonomy = \'category\', $order_by = \'id\', $skip_empty = true ) {
$this->sorted_taxonomies = get_terms(
$taxonomy,
array(
\'get\' => $skip_empty ? \'\' : \'all\',
\'fields\' => \'ids\',
\'hierarchical\' => false,
\'order\' => \'ASC\',
\'orderby\' => $order_by,
)
);
}
/**
* @param int Taxonomy ID.
* @return int|bool Next taxonomy ID or false if this ID is last one. False if this ID is not in the list.
*/
public function next( $taxonomy_id ) {
$current_index = array_search( $taxonomy_id, $this->sorted_taxonomies );
if ( false !== $current_index && isset( $this->sorted_taxonomies[ $current_index + 1 ] ) )
return $this->sorted_taxonomies[ $current_index + 1 ];
return false;
}
/**
* @param int Taxonomy ID.
* @return int|bool Previous taxonomy ID or false if this ID is last one. False if this ID is not in the list.
*/
public function previous( $taxonomy_id ) {
$current_index = array_search( $taxonomy_id, $this->sorted_taxonomies );
if ( false !== $current_index && isset( $this->sorted_taxonomies[ $current_index - 1 ] ) )
return $this->sorted_taxonomies[ $current_index - 1 ];
return false;
}
}