0

我要在边栏中列出带有图像的类别这就是我的做法(并且它有效)我这样做是因为我有某些我不想显示的类别!

<?php $latests = new WP_Query('posts_per_page=2&ignore_sticky_posts=1&cat=12'); ?>
<?php echo get_cat_name(12); ?>
<?php while ($latests->have_posts()) : $latests->the_post(); ?>
<?php if ( has_post_thumbnail() ) { the_post_thumbnail('sidebarcat'); } ?>
<?php the_title(); ?>
<?php endwhile; wp_reset_postdata(); ?>

但我需要为每个类别复制过去的代码......我猜所有这些只更改数字的代码都是一个好习惯。有没有其他方法可以做到?

我已经尝试过使用 foreach 但它似乎是错误的

<?php $latests = new WP_Query('posts_per_page=2&ignore_sticky_posts=1&cat=12'); ?>
<?php foreach($latests as $latest) :?>

    <?php while ($latests->have_posts()) : $latests->the_post(); ?>
<?php if ( has_post_thumbnail() ) { the_post_thumbnail('sidebarcat'); } ?>
<?php the_title(); ?>

    <?php endwhile; wp_reset_postdata(); ?>
<?php endforeach; ?>
4

2 回答 2

2

好吧,你可以这样做:

<ul>
<?php
$cat_args=array(
//  'include' => '3,6,9', // display only these categories
  'exclude' => '3,6,9', // display all categories except categories 3,6,9
  'orderby' => 'name', // the order 
  'order' => 'ASC' // asc or desc
);

$categories=get_categories($cat_args);
  foreach($categories as $category) {
    $args=array(
      'showposts' => 2, // how many posts you want to display 
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
    );

$posts=get_posts($args);
      if ($posts) { 
        echo '<h3> <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in: %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </h3> ';
        foreach($posts as $post) {
          setup_postdata($post); 
?>

    <li>
        <div>
            <div><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('sidebarcat'); } ?></a></div>
            <div><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></div>
        </div>
    </li>


          <?php
        } // close foreach 
      } // close if  
    } // close foreach 
?>
</ul>
于 2013-05-13T15:11:25.487 回答
0

最简单的方法就是这样

<?php wp_list_categories('orderby=name&exclude=3,5,9,16'); ?> 

因此,这将返回除您指定的类别之外的所有类别。在此之后,您可以获得您想要的类别和所有的实际图像。

于 2013-05-13T14:17:28.463 回答