开发者

Wordpress query one post from each parent category (exclude child categories)

开发者 https://www.devze.com 2023-03-03 18:45 出处:网络
I\'m trying to list one post from each parent category in Wordpress but I can\'t seem to figure out how to alter this code to exclude child categories. Basically I\'m listing the name of the category,

I'm trying to list one post from each parent category in Wordpress but I can't seem to figure out how to alter this code to exclude child categories. Basically I'm listing the name of the category, then a post thumb, an excerpt, and a read more button for each parent category. I cannot just exclude child categories by category id because this site is for a client who will be adding sub categories later on. Please help, thanks!

$num_cats_to_show = 10;
$count = 0;
$taxonomy = 'category';//  e.g. post_tag, category
$param_type = 'category__in'; //  e.g. tag__in, category__in
$term_args=array(
  'orderby' => 'name',
  'order' => 'ASC',
);
$terms = get_terms($taxonomy, array( 'exclude' => '15,1'),$term_args );
if ($terms) {
  foreach( $terms as $term ) {
    $args=array(
      "$param_type" => array($term->term_id),
      'post_type' => 'post',
      'pos开发者_运维技巧t_status' => 'publish',
      'posts_per_page' => 1,
      'caller_get_posts'=> 1,
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      $count ++;
      if ($count <= $num_cats_to_show) {
        while ($my_query->have_posts()) : $my_query->the_post(); 


I think you want to get only those terms that have a parent equal to 0 (no parent).

$term_args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'parent' => 0
);
$terms = get_terms($taxonomy, $term_args);

I don't think you can exclude terms by ID with get_terms, but you can just reject the relevant terms in your loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消