【问题标题】:List Wordpress categories in sidebar with image用图像在侧边栏中列出 Wordpress 类别
【发布时间】:2013-05-13 13:05:16
【问题描述】:

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

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

【问题讨论】:

    标签: php wordpress categories


    【解决方案1】:

    好吧,你可以这样做:

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

    【讨论】:

      【解决方案2】:

      最简单的方法就是这样

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

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

      【讨论】:

      • 是的,但我需要从每个类别中获取最后 2 个帖子......而且肯定这是不可能的。
      • 如果你拿数组,在这个数组上做一个foreach,你将能够查询所有这些类别的最后2个帖子。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      相关资源
      最近更新 更多