【问题标题】:Get all terms in a custom Wordpress Query?获取自定义 Wordpress 查询中的所有术语?
【发布时间】:2014-03-27 19:07:45
【问题描述】:

我知道如何获取所有 Wordpress 术语,但我需要结果的“过滤”版本。是否可以获得 Wordpress 查询结果中的所有术语?我在这里有这个查询:

<?php
   $args=array(
  'post_type' => 'gw_activity',
  'post_status' => 'publish',
  'orderby' => 'date',
  'meta_query' => array(
     'relation' => 'AND',
      array(
         'key' => 'activity_category',
         'value' => 'mindful_life',
         'compare' => '='
      )
   ), 
  'posts_per_page' => 10
);
$my_query = null; 
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { 
 $all_terms = array();
  while ($my_query->have_posts()) : $my_query->the_post(); ?>      
  <?php $terms = wp_get_post_terms( $my_query->post->ID, array( 'gw_activity_tag' ) ); ?>
  <?php       
        foreach ( $terms as $term ) {
            $all_terms[] = $term->name;
        }        
  ?>                                            
  <?php endwhile; }
  wp_reset_query();
?>
<!-- End Custom Query -->
<?php
    $unique_terms = array_unique( $all_terms ); 
    $result = array_unique($unique_terms);
    foreach ($result as $value) {
        echo $value . '<br />';
    }

?>

但我不知道如何运行查询并在其中添加“Where”子句,就像使用 MySQL 一样。任何帮助/建议,甚至指出我正确的方向都将不胜感激。我卡住了

【问题讨论】:

    标签: php wordpress tags


    【解决方案1】:

    检查这个函数:wp_get_post_terms()

    假设您的帖子支持 tax_atax_b 两种分类法,您可以尝试这样的方法,正是您写评论的地方:

    <?php $terms = wp_get_post_terms( $query->post->ID, array( 'tax_a', 'tax_b' ) ); ?>
    
    <?php foreach ( $terms as $term ) : ?>
        <p><?php echo $term->taxonomy; ?>: <?php echo $term->name; ?></p>
    <?php endforeach; ?>
    

    这将打印查询检索到的每个帖子的所有术语。


    编辑

    如果您想要的是查询检索到的所有帖子中的所有术语,您可以将值存储在一个数组中,然后使用类似 array_unique() 之类的函数,如下所示: p>

    $all_terms = array();
    foreach ( $terms as $term ) {
        $all_terms[] = $term->name;
    }
    
    // ... and outside the WHILE loop
    $result = array_unique( $all_terms );
    foreach ( $result as $term ) {
        echo $term . '<br/>;
    }
    

    【讨论】:

    • 这行得通,但不幸的是它引入了重复的术语。有什么建议吗?
    • 这也有效,但我仍然在输出中得到重复的术语。
    • @TripsLeft,真的吗?你在打印$unique_terms吗?
    • @TripsLeft,首先你使用了两次array_unique,只做:$result = array_unique($all_terms);。当然,您应该调用 array_unique 并在 while 循环外部打印结果!
    • @TripsLeft,没问题!请注意,您仍然调用array_unique 两次,这也可以,但没有任何意义!请记住,如果您对此感到满意,可以将答案标记为已接受;)
    猜你喜欢
    • 2012-04-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    相关资源
    最近更新 更多