2013-05-13 33 views
0

我要在邊欄中列出帶有圖像的類別這是我如何做的(並且它的工作原理)我這樣做是因爲我有某些我不想顯示的類別!列出邊欄與圖像中的WordPress類別

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

好吧,你可以這樣說:

<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> 
+0

這個10倍隊友就像我想要的那樣工作。謝謝 – 2013-05-13 15:21:59

0

最簡單的方法就是這樣

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

所以,這將返回所有不包括一個你的類別指定。在此之後,你可以得到你想要的類別和所有的實際圖像。

+0

是的,但我需要從每個類別獲得最後的2個職位...並確保用是不可能的。 – 2013-05-13 14:48:11

+0

如果你拿這個數組,在這個數組上做一個foreach,你將能夠查詢所有這些類別的最後2個帖子。 – tehknox 2013-05-13 19:45:50