【问题标题】:WordPress WP QUERY with OR condition带有 OR 条件的 WordPress WP QUERY
【发布时间】:2021-08-21 08:26:54
【问题描述】:

在我的网站上,有几个带有默认博客帖子的自定义帖子类型。在博客文章中,有很多类别。

其中一种帖子类型是webinar。我喜欢查询帖子类型webinar的所有帖子以及类别ID为43的博文

我尝试了以下方法但不起作用。

1:

$query = new WP_Query(array(
  'post_type' => array('webinar'), // I need all post from webinar
  'cat' => '43', // I need all blog post under this category (Post type post category id 43)
);

结果:未找到帖子

2:

$query = new WP_Query(array(
  'post_type' => array('webinar','post'), // I need all post from webinar
  'cat' => '43', // I need all blog post under this category (Post type post category id 43)
);

结果:只有类别 id 43 的帖子,没有帖子类型 webinar 的帖子

我需要类似以下的东西:

$query = new WP_Query(array(
  array(
    'relation' => 'OR',
    array(
      'post_type' => array('webinar')
    ),
    array(
     'post_type' => 'post',
     'cat' => '43'
    )
  )
));

我该怎么做?

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    解决方案 1

    // This could be cached in the site option
    // in case this code will take a long time.
    $webinar_terms = get_terms([
        'taxonomy' => '{webinar_tax_name}',
        'hide_empty' => true,
    ]);
    
    $allowed_terms_ids = [];
    
    foreach ( $webinar_terms as $term )
    {
        $allowed_terms_ids[] = $term->term_id;
    }
    
    // Add post cat to allowed terms.
    $allowed_terms_ids[] = 43;
    
    $query = new WP_Query([
      'post_type' => ['webinar','post'],
      'cat' => $allowed_terms_ids,
    ]);
    

    注意

    这仅适用于所有webinar 帖子将分配给至少1 个{webinar_tax_name} 术语的情况。

    解决方案 2

    您可以使用posts_request 钩子并在您的示例中为您的 1 个查询更新 SQL。但我更喜欢第一种解决方案,因为它对其他开发人员来说会更清楚。

    【讨论】:

      【解决方案2】:
      $posts = get_posts([
        'post_type' => 'webinar',
        'post_status' => 'publish',
        'numberposts' => -1
         
      ]);
      

      【讨论】:

      【解决方案3】:
      $post_data = get_posts( [
          'post_type' => ['webinar', 'post'],
          'posts_per_page' => - 1,
          'tax_query' => array(
             'taxonomy' => 'category',
             'field'    => 'term_id',
             'terms'    => '43'
           ),
      ] );
      

      这样的东西会起作用吗?我没有测试过这个,所以可能需要玩一下。

      如果您不想使用 get_posts 则可以随时使用新的 WP_Query 但需要修改

      【讨论】:

      • 我猜我的第二个代码示例和你的完全一样。
      • 它们很相似,但这个应该适合你
      猜你喜欢
      • 2018-10-04
      • 2021-12-13
      • 2011-04-12
      • 2021-04-30
      • 2011-09-09
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多