假设您在$country_tag 中获得了正确的值,并且假设(根据您的问题)$country_tag 是标签 name(而不是标签 slug 或 ID),那么您必须在 get_posts 中使用 Taxonomy Parameters,或者首先获取标签的 ID 或 slug。你可以使用get_term_by来做到这一点
另外,在对帖子进行操作之前,您需要拨打setup_postdata。
我建议先使用get_term_by,这样你可以先检查标签是否存在,如果不存在则输出消息。
$country_tag = get_the_title();
$tag = get_term_by( 'name', $country_tag, 'post_tag' );
if ( ! $country_tag || ! $tag ) {
echo '<div class="error">Tag ' . $country_tag . ' could not be found!</div>';
} else {
// This is not necessary. Remove it...
// global $wp_query;
$args = array(
'tag__in' => (int)$tag->term_id,
'posts_per_page' => -1
);
$posts = get_posts( $args );
// be consistent - either use curly braces OR : and endif
foreach( $posts as $post ) {
// You can't use `the_title`, etc. until you do this...
setup_postdata( $post );
// This if statement is completely unnecessary, and is incorrect - it's an assignment, not a conditional check
// if ( $posts = $country_tag ) {
the_title();
// }
}
}
以上我推荐get_term_by 方法,因为它允许您首先验证是否存在具有该名称的标签。如果您 100% 确信总有一个标签对应于页面标题,则可以使用分类参数(如下所示):
$country_tag = get_the_title();
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'name',
'terms' => $country_tag
)
),
'posts_per_page' => -1
);
$posts = get_posts( $args );
foreach( $posts as $post ) {
setup_postdata( $post );
the_title();
}