【问题标题】:WordPress Can't get all the posts which respects tags and categories conditionsWordPress 无法获取所有尊重标签和类别条件的帖子
【发布时间】:2013-11-09 13:13:49
【问题描述】:

我创建了一个自定义类型的帖子,我想获取属于某个类别和一个标签的所有帖子。不幸的是,我不知道为什么它只返回一个帖子(我应该至少有 3 或 4 个)

这是我的代码:

$tag = $_GET["tag"];
$cat = $_GET["cat"];

$args = array(
    'post_type' => 'post_product',
    'post_status' => 'publish',
    'numberposts' => -1,
    array(
        array(
            'taxonomy' => 'cating'
        ),
        array(
            'taxonomy' => 'tagging')
    )
);

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ):

    while ( $custom_query->have_posts() ) :
        $custom_query->the_post();

        $product_terms = wp_get_object_terms(get_the_ID(), 'cating');
        $product_terms_tag = wp_get_object_terms(get_the_ID(), 'tagging');

        if(!empty($product_terms) && !empty($product_terms_tag)){
            if(!is_wp_error( $product_terms ) && !is_wp_error( $product_terms_tag )){

                foreach($product_terms as $term){
                    if(strcmp($term->name, $cat) == 0) {

                        foreach($product_terms_tag as $term_tag){
                            if(strcmp($term_tag->name, $tag) == 0) {

                                // display here

                            }
                        }
                    }
                }
            }
        }
    }
}

有谁知道为什么我只收到一个帖子或什么都没有,因为它们是尊重这些条件的帖子。

谢谢。

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    将 $post_count 添加到您的 $args 数组中,其中包含您想要的帖子数

    【讨论】:

      【解决方案2】:

      您的Taxonomy Query parameters 格式不正确。而且您也没有使用任何 $_GET 变量。

      假设您通过 $_GET 获取术语 ID,它应该类似于:

      $args = array(
          'post_type' => 'post_product',
          'post_status' => 'publish',
          'posts_per_page' => -1,
          'tax_query' => array(
              'relation' => 'AND',
               array(
                  'taxonomy' => 'tagging',
                  'field' => 'id',
                  'terms' => (int) $tag
              ),
              array(
                  'taxonomy' => 'cating',
                  'field' => 'id',
                  'terms' => (int) $cat
              )
          )
      );
      

      【讨论】:

      • 感谢您的回答。我实际上得到了术语名称。我在测试strcmp($term->name, $cat) == 0 中使用了我的get 变量,所以我的想法是通过循环检索所有帖子并根据条件显示它们。我已经尝试了您的代码并删除了条件,结果不尊重$cat 值..
      • 您也可以在field参数中使用slug代替id
      • 你也应该使用posts_per_page而不是numberposts
      猜你喜欢
      • 2018-06-24
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      相关资源
      最近更新 更多