用我当前 post 的标签之一显示 posts

Display posts with one of the tags of my current post

我的 WP 站点上有几个 post,每个 post 可以有 1-n 个标签。

在过去的几个小时里,我正在尝试显示最新的 3 个 post 以及我当前 post.

的标签之一

样本:

Post A 有标签“Apple”、“Banana”、“Orange”

Post B 有标签“香蕉”、“葡萄柚”

Post C 有标签“Apple”、“Grapefruit”


如果我在 Post A 上,我想显示 Post B 和 C 作为我的相关 posts(因为 B 有标签“Banana”并且 post C 有标签“Apple”)。

如果我在 Post B 上,我想显示 Post C 作为我的相关 post(因为 C 有标签“Grapefruit”)

到目前为止我尝试过的:

function twr_related_posts__tag() { 

    $content = '<h3 class="mt-5">Related Posts</h3> ';

    $myTopics_id = "";
    $myTopics_array = [];

    /* Get all Tag IDs of current post */
    $myTopics = get_the_tags();

    if ($myTopics) {
        foreach($myTopics as $tag) {                             
            $myTopics_array[] = $tag->term_id;
        }
    }
    
    
    $args = array(  
        'tag__in'        => $myTopics_array,
        'tag__not_in'    => array( 16, 17, 18 ), 
        'orderby'        => 'date',
        'order'          => 'DESC',
        'posts_per_page' => -1 
    );

    $query = new WP_Query( $args );
    

    while ( $query -> have_posts() ) : $query -> the_post();
      
        $content .= '<p>'. get_the_title() .'</p>';

    endwhile; 
    


    wp_reset_query();

    return $content;

}

add_shortcode('related_posts__tag','twr_related_posts__tag');

我正在获取 post 标签的 ID,并将它们放入一个数组中。 将数组放在 WP_Query 的 'tag__in' 子句中。 显示结果集的标题。

但是结果集是错误的。 首先,它将当前 post 显示为相关 post(不应该是这种情况,应该排除当前 post)。而其他的结果都是错误的。

我需要更改什么?

'tag__in'        => array( $myTopics_id ),

这样一来,您实际上并没有提供一组 post 个 ID,而是一个只有一个元素的数组,因为 $myTopics_id 是一个由逗号分隔的 ID 组成的字符串值。

至于没有得到您想要的所有 post,事实证明这是为 tag__intag__not_in 指定的标签 ID 之间的重叠。由于您在此处获得了不需要的标签 ID 的固定列表,因此仅通过 tag__in 进行过滤并从包含当前 post 标签的数组中删除不需要的 ID 是有意义的, array_diff 可以提供帮助:

$tagsIn = array_diff( $myTopics_array, [16, 17, 18] );

要排除当前 post 本身,您只需添加一个 post__not_in 过滤器即可。将 global $post; 放在函数的开头会将全局 post 对象导入函数范围,之后您可以使用 $post->ID 获取当前查看的 post 的 ID。

如果有人正在寻找类似的解决方案,这里是问题的完整代码。再次感谢@CBroe,超级有帮助!

function twr_related_posts__tag() { 
    
    global $post;

    $content = '<h3 class="mt-5">Related Posts</h3> ';

    $myTopics_id = "";
    $myTopics_array = [];

    /* Get all Tag IDs of current post */
    $myTopics = get_the_tags();

    if ($myTopics) {
        foreach($myTopics as $tag) {
            $myTopics_array[] = $tag->term_id;
        }
    }
    
    
    $args = array(  
        'tag__in'        => array_diff( $myTopics_array, [16, 17, 18] ),  // use array, but exclude specific tag ids
        'post__not_in'   => array( $post->ID ),
        'orderby'        => 'date',
        'order'          => 'DESC',
        'posts_per_page' => 3 
    );

    $query = new WP_Query( $args );
    

    while ( $query -> have_posts() ) : $query -> the_post();
      
        $content .= '<p>'. get_the_title() .'</p>';

    endwhile; 
    


    wp_reset_query();

    return $content;

}

add_shortcode('related_posts__tag','twr_related_posts__tag');