基于@birgire总是有用的评论,我确实为您编写了一个变通方法。我要做的是首先找到与搜索字符串匹配的术语。然后,根据找到的术语,我将在这些术语中进行查询。
function wpse_posts_by_tagname( $string ) {
// Let\'s find every tag that has \'coffee\' in it\'s name
$term_args = array(
\'taxonomy\' => \'post_tag\',
\'fields\' => \'ids\',
\'name__like\' => $string,
// \'description__like\' => $string, // You can also search in description.
// \'search\' => $string, // We can even search in the term\'s name!
);
$terms = get_terms( $term_args );
// Let\'s make an array of term IDs
if ( empty( $terms ) || is_wp_error( $terms ) )
esc_html_e( \'No matches found\', \'text-domain\' );
// Alright we got\'em, now query based on these
$query_args = array(
\'post_type\' => \'post\',
\'tag__in\' => (array) $terms,
\'posts_per_page\' => 10 // Optional limitation of posts per page
);
$tag_query = new WP_Query( $query_args );
if( $tag_query->have_posts() ){
while( $tag_query->have_posts() ){
$tag_query->the_post();
the_title(
sprintf( \'<h2><a href="%s">\', esc_url( get_permalink() ) ),
\'</a></h2>\'
);
}
wp_reset_postdata();
} else {
esc_html_e( \'No matches found\', \'text-domain\' );
}
}
另外,值得注意的是,您应该使用
WP_Query
而不是
query_posts
. 互联网上关于这方面的文章层出不穷,所以我跳过这部分。