在一个项目中遇到了这个问题,但从未在网上找到解决方案——我的 PHP 不是最漂亮的,但它可以解决问题。
这是 Katie 建议的过滤器,我也在几个支持论坛中遇到过。这进入你的functions.php:
add_filter( 'getarchives_where', 'customarchives_where' );
add_filter( 'getarchives_join', 'customarchives_join' );
function customarchives_join( $x ) {
global $wpdb;
return $x . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
}
function customarchives_where( $x ) {
global $wpdb;
$categories = get_terms( 'taxonomy-name', 'orderby=id' );
$includeIds;
$i = 0;
foreach($categories as $category) {
if($i != 0) $includeIds .= ',';
$includeIds .= $category->term_id;
$i++;
}
return $x . " AND $wpdb->term_taxonomy.taxonomy = 'taxonomy-name'
AND $wpdb->term_taxonomy.term_id IN ($includeIds)";
}
在第二个函数中,将 taxonomy-name 替换为您的实际自定义分类的名称。
您的自定义分类中的所有术语 ID 都被捕获在一个字符串中;其余的操作与原始函数相同——只有自定义分类法中的类别列表包含在 wp_get_archives() 列表中。您还可以调整代码以排除它们(上面的第一个示例)。
如果您只希望wp_get_archives() 列表的一个实例执行此操作,只需跳过functions.php 中应用过滤器的前两行代码。然后,当您使用 wp_get_archives() 标记时,应用它之前的过滤器,然后将它们删除:
<?php
add_filter( 'getarchives_where', 'customarchives_where' );
add_filter( 'getarchives_join', 'customarchives_join' );
wp_get_archives();
remove_filter( 'getarchives_where', 'customarchives_where' );
remove_filter( 'getarchives_join', 'customarchives_join' );
?>