Based on @birgire’s always-useful comments, I did write a workaround for you. What I’m doing is to first find the terms that match the search string. Then, based on the found terms I will do a query in those.
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="https://wordpress.stackexchange.com/questions/274014/%s">', esc_url( get_permalink() ) ),
'</a></h2>'
);
}
wp_reset_postdata();
} else {
esc_html_e( 'No matches found', 'text-domain' );
}
}
Also it’s worth noting that you should use WP_Query
instead of query_posts
. There are endless articles on the internet about this, so I’m just gonna skip this part.