列出带有图像的侧栏中的Wordpress类别

时间:2013-05-13 13:05:16

标签: php wordpress categories

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

<?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; ?>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

最简单的方法就是那样

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

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