【问题标题】:Related posts wordpress loop excluding certain tags相关帖子 wordpress 循环不包括某些标签
【发布时间】:2012-03-13 23:13:55
【问题描述】:

有没有办法从相关帖子循环中排除某些标签,而它仍然可以找到其他标签?这是我拥有的代码,但我知道没有像 tag_slug__not_in 这样的值,但我不想使用 ID,因为它们很乱,有没有办法通过 slug 排除标签,通常这会工作,因为我我是说包含的所有标签都是任何标签吗?非常感谢任何帮助!

<?php  //for use in the loop, list 5 post titles related to first tag on current post
$backup = $post;  // backup the current object
$tags = wp_get_post_tags($post->ID);
$tagIDs = array();
if ($tags) {
$tagcount = count($tags);
for ($i = 0; $i < $tagcount; $i++) {
  $tagIDs[$i] = $tags[$i]->term_id;
}
$args=array(
  'tag__in' => $tagIDs,
  'tag_slug__not_in' => array('investing', 'investment', 'travel', 'shopping', 'retail',       'organisations', 'governments', 'government', 'individuals', 'entrepeneurs', 'companies', 'markets', 'finance', 'clean-tech', 'money', 'world', 'business'),
  'post__not_in' => array($post->ID),
  'showposts'=>5,
  'caller_get_posts'=>1,
  'post_type' => array('post','indepth','feature','interview')
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<h3>Related Articles</h3>
<?php  while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <ul><li><p><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></p></li>
    </ul>
  <?php endwhile;
} else { ?>

<?php }
}
$post = $backup;  // copy it back
wp_reset_query(); // to use the original query again
?>

【问题讨论】:

    标签: wordpress loops tags


    【解决方案1】:

    我同意,他们没有 tag_slug__not_in 参数是很愚蠢的。

    无论如何,我认为您可以使用 WP_Query 的 tax_query 参数来实现您想要做的事情。以下代码未经测试:

    $args=array(
      'post__not_in' => array($post->ID),
      'showposts'=>5,
      'caller_get_posts'=>1,
      'post_type' => array('post','indepth','feature','interview'),
      'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'post_tag',
            'field' => 'id',
            'terms' => $tagIDs
        ),
    
        array(
            'taxonomy' => 'post_tag',
            'field' => 'slug',
            'terms' => array('investing', 'investment', 'travel', 'shopping', 'retail', 'organisations', 'governments', 'government', 'individuals', 'entrepeneurs', 'companies', 'markets', 'finance', 'clean-tech', 'money', 'world', 'business'),
            'operator' => 'NOT IN'
        )
      )
    );
    

    如果这不起作用,您可能需要尝试阅读更多关于Taxonomy Parameters in WP_Query 的内容,看看在tax_query 数组中添加relation 键是否可以进一步帮助解决您的问题。

    【讨论】:

    • 很棒,在一定程度上有效,但它本质上的作用是或多或少地取消了一切。我想做的是让它忽略这些标签,但要注意其他带有该标签的帖子中的标签。老实说,我不确定这是否真的可行,因为很明显,它是说不要显示带有此标签的帖子,当我的意思是更多时,如果帖子与您只有这个标签,请不要显示帖子。这有意义吗?
    • 我基本上希望它忽略这些标签,而不是帖子,以便它仍然在这些帖子中搜索其他相关标签。狡猾的一个。嗯,我不确定这是否可能,现在我正在考虑。
    • 检查我更新的答案。我想这可能就是你想要做的。
    • 我认为这使得 NOT IN 不起作用,因为它再次与所有标签相关,这很棘手:(
    • 能否修改您的帖子并举例说明在给定某些帖子和标签的情况下会发生什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    相关资源
    最近更新 更多