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

Php 显示标记与页面标题匹配的帖子,php,wordpress,loops,tags,custom-post-type,Php,Wordpress,Loops,Tags,Custom Post Type,我正在尝试创建一个循环,该循环显示一个帖子列表,其中的标签与循环所在的页面标题匹配 例如,我有一个名为“国家”的自定义帖子类型列表,在每个国家我都有一个最近发布的帖子列表。对于每个国家,我都希望显示带有与该国家相关标签的帖子。因此,如果一篇文章包含标签“UK”,那么只有这些文章才会显示在“UK”页面上 这是到目前为止我的代码,根本不起作用 $country_tag = get_the_title(); global $wp_query; $args = array(

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

例如,我有一个名为“国家”的自定义帖子类型列表,在每个国家我都有一个最近发布的帖子列表。对于每个国家,我都希望显示带有与该国家相关标签的帖子。因此,如果一篇文章包含标签“UK”,那么只有这些文章才会显示在“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\u标签
中得到了正确的值,并且假设(根据您的问题)
$country\u标签
是标签名(而不是标签slug或ID),那么您必须在get\u帖子中使用,或者首先获取标签的ID或slug。您可以使用

此外,在你可以操作岗位之前,你需要打电话

我建议首先使用
get\u term\u 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();
        // }
    }
}

我在一篇帖子中添加了标签“联合王国”,我看到的页面标题是“联合王国”。然而,使用您友好地组合在一起的循环,不幸的是没有返回任何结果。。。您提供的第一个循环有效。第二个循环没有返回任何内容。。。我想是你干的:)
$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();
}