前提是要在注册文章类型的时候绑定taxonomies为post_tag
‘taxonomies’ => array(‘post_tag’),
/**
* Advanced version that works with multiple custom post types
* and handles both tags and categories
*
* @param WP_Query $query The WordPress query object
*/
function include_all_post_types_in_archives($query) {
// Only modify the main query on the frontend
if (is_admin() || !$query->is_main_query()) {
return;
}
// For tag or category archives
if ($query->is_tag() || $query->is_category()) {
// Get what taxonomy we're currently viewing
$taxonomy = $query->is_tag() ? 'post_tag' : 'category';
// Find all post types that have this taxonomy registered
$post_types = array();
$registered_post_types = get_post_types(array('public' => true), 'objects');
foreach ($registered_post_types as $post_type) {
$post_type_taxonomies = get_object_taxonomies($post_type->name);
// If this post type has the current taxonomy registered
if (in_array($taxonomy, $post_type_taxonomies)) {
$post_types[] = $post_type->name;
}
}
// Only modify the query if we found post types
if (!empty($post_types)) {
$query->set('post_type', $post_types);
}
}
}
// Uncomment this line to use the advanced version instead
add_action('pre_get_posts', 'include_all_post_types_in_archives', 10);
WP开发教程 WordPress导师在线教程