显示标签与页面标题匹配的帖子

Display posts where tag matches page title

我正在尝试创建一个循环来显示 post 列表,其中的标签与循环所在的页面标题相匹配。

例如,我有一个名为 'countries' 的自定义 post 类型列表,在每个国家/地区,我都有一个最近的 post 列表。对于每个国家/地区,我想显示 posts 以及与该国家/地区相关的标签。因此,如果 post 包含标签 'UK',那么只有这些 post 应该显示在 'UK' 页面上。

到目前为止,这是我的代码,但根本不起作用...

    $country_tag = get_the_title(); 

    global $wp_query;
    $args = array(
    'tag__in' => 'post_tag', //must use tag id for this field
    'posts_per_page' => -1); //get all posts

    $posts = get_posts($args);
    foreach ($posts as $post) :
    //do stuff 
    if ( $posts = $country_tag ) {
    the_title();
    }
    endforeach;

假设你在$country_tag中得到了正确的值,并且假设(根据你的问题)$country_tag 是标签 name(而不是标签 slug 或 ID),那么您必须使用 Taxonomy Parameters in your get_posts, or first get the ID or slug of the tag. You can do this using get_term_by

此外,在对 post 进行操作之前,您需要调用 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();
}