【问题标题】:Display posts where tag matches page title显示标签与页面标题匹配的帖子
【发布时间】:2016-04-05 11:44:54
【问题描述】:

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

例如,我有一个名为“国家/地区”的自定义帖子类型列表,在每个国家/地区我都有一个最近发布的帖子列表。对于每个国家,我想显示带有与该国家相关的标签的帖子。因此,如果帖子包含标签“英国”,那么只有这些帖子应该显示在“英国”页面上。

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

    $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;

【问题讨论】:

    标签: php wordpress loops tags custom-post-type


    【解决方案1】:

    假设您在$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();
    }
    

    【讨论】:

    • 我将标签“英国”添加到帖子中,并且我正在查看的页面标题为“英国”。但是,不幸的是,使用您精心组合的循环不会返回任何结果。
    • 等待忽略...您提供的第一个循环有效。第二个循环什么也没返回……我想你做到了:)
    猜你喜欢
    • 2011-09-18
    • 1970-01-01
    • 2014-12-22
    • 2019-11-09
    • 2018-01-18
    • 2017-08-24
    • 2021-11-07
    • 2014-04-21
    • 1970-01-01
    相关资源
    最近更新 更多