【问题标题】:WP_Query sort category by termWP_Query 按术语排序类别
【发布时间】:2015-01-07 16:52:12
【问题描述】:

我想让下面的代码对我的自定义 posttype(产品类型)进行排序。 这样我的活动页面将只显示带有“石油”一词的帖子,而不是“燃料”和“轮胎”。

$args = array(
  'post_type' => 'Products',
  'posts_per_page' => -1
);

$my_query = new WP_Query( $args );

if ($my_query->have_posts()) {
  while($my_query->have_posts() ) {                           
    echo '<div class="custom-post">';
    $my_query->the_post();
    echo '<p>' . the_content() . '</p>';
    the_post_thumbnail();
    echo '</div>';
  }
  wp_reset_postdata();
}

// 编辑,作为对以下 3 个答案的回复

我假设 foreach 循环是 WP_Query 方法的替代品,但 tax_query 对我来说是新的,现在我知道它存在,我在 codex 中查找它,但它仍然无法工作。老实说,我认为这就像我在 tax_query 中错误地命名一样简单,所以我将在这里展示我的分类代码:

function my_custom_taxonomies() {
    register_taxonomy(
        'product-type',
        'products',
        array(
            'label' => 'Type of Product',
            'rewrite' => array( 'slug' => 'race-products' ),
            'hierarchical' => true,
        )
    );
}

add_action( 'init', 'my_custom_taxonomies' );

以及对 $args 的更改:

$args = array(
    'post_type' => 'Products',
    'posts_per_page' => -1,
    'tax_query' => array( 
        array(
            'taxonomy' => 'product-type',
            'field' => 'slug',
            'terms' => 'oil'
        ),
    ),
);

【问题讨论】:

    标签: php wordpress web


    【解决方案1】:

    试试下面的代码:

    <?php
        $myposts = get_posts(array(
            'showposts' => -1,
            'post_type' => 'Products',
            'tax_query' => array(
                array(
                'taxonomy' => 'products_cat',
                'field' => 'slug',
                'terms' => 'oil'
                   );
            )
         )
        );
    
        foreach ($myposts as $mypost) {
              echo $mypost->post_title . '<br/>';
              echo $mypost->post_content . '<br/>';
              echo  get_the_post_thumbnail( $mypost->ID );
        }
    ?>
    

    【讨论】:

    • 已修复,只是我将母语“Olie”与“Oil”混为一谈,非常感谢您提供的 tax_query 信息! :)
    【解决方案2】:
    $loop = new WP_Query(array(
        'posts_per_page' => 10,
        'post_type' => 'product_type',
        'order' => 'DESC',
        'orderby' => 'id',
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'your_texonomy',
                'field' => 'slug',
                'terms' => 'Oil',
            ),
        ),));
    

    【讨论】:

      【解决方案3】:

      您需要在查询中尝试以下参数。

      $args = array(
       'post_status' = 'publish',
       'tax_query' = array(
           'taxonomy' => 'categories',
           'field'    => 'id',
           'term'     =>  'category id here'
       )
      );
      $the_query = wp_query($args);
      

      【讨论】:

        猜你喜欢
        • 2015-05-13
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多