仅仅抓取一个作者的所有帖子,然后过滤它们,只返回一个类别列表,这有点笨拙。如果您希望使用侧边栏中的默认小部件,并让作者仅在作者模板上对其进行过滤,那么我建议使用以下方法。
首先,过滤标签和类别小部件查询中的类别和标签。
add_filter( \'widget_tag_cloud_args\', \'filter_categories_by_author\' );
add_filter( \'widget_categories_dropdown_args\', \'filter_categories_by_author\' );
add_filter( \'widget_categories_args\', \'filter_categories_by_author\' );
function filter_categories_by_author( $args ){
// only process if on the author template
if( is_author() ){
$author_id = get_the_author_meta( \'ID\' );
$taxonomy = !empty( $args[\'taxonomy\'] ) ? $args[\'taxonomy\'] : \'category\';
// filter by including only IDs associated to the author
$args[\'include\'] = get_taxonomy_ids_by_author( $author_id, $taxonomy );
}
return $args;
}
然后使用dependent方法检索由用户ID过滤的分类ID。
function get_taxonomy_ids_by_author( $user_id, $taxonomy = \'category\' ){
global $wpdb;
return $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT(terms.term_id) as ID
FROM $wpdb->posts as posts
LEFT JOIN $wpdb->term_relationships as relationships ON posts.ID = relationships.object_ID
LEFT JOIN $wpdb->term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN $wpdb->terms as terms ON tax.term_id = terms.term_id
WHERE 1=1 AND (
posts.post_status = \'publish\' AND
posts.post_author = %d AND
tax.taxonomy = \'%s\' )
ORDER BY terms.name ASC
", $user_id, $taxonomy ) );
}
资料来源:
https://gist.github.com/codearachnid/9655690