【记录】WordPress首页循环输出分类目录,以及分类下的文章列表,同时排除文章列表中带有自定义字段的文章。
下图“今日推荐”中的文章,来自于“创业资讯”和“创业指导”这两个分类,为了避免出现重复链接,可以给“今日推荐”中的文章设置自定义字段(例如,设置两个自定义字段,名称为type,值分别为hot和pic),然后“今日推荐”的头条文章调用hot,下面的文章列表调用pic。
然后在“创业资讯”、“创业指导”这两个文章列表里,排除带有“type”字段的文章。
实现代码:
<div> <div> <h2>最新发布</h2> <?php query_posts('cat=1&showposts=1&meta_value=hot'); ?> //cat=1,分类目录ID为1,如不需限制分类,删除cat=1即可;showposts=1,调用一篇;meta_value=hot,自定义字段值为hot的文章; <?php $query_index = 0; while (have_posts()) : $query_index++;the_post(); ?> <h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3> <p><?php echo mb_strimwidth(strip_tags(apply_filters('content', $post->post_content)), 0, 150,"..."); ?></p> //文章描述,超出150个字符后显示省略号; <?php endwhile; wp_reset_query(); ?> <ul> <?php query_posts('&showposts=10&meta_key=type&meta_value=pic'); //调用自定义字段名称为type,值为pic的10篇文章; if(have_posts()) : while (have_posts()) : the_post(); ?> <li><a href="<?php the_permalink();?>"><?php the_title();?></a></li> <?php endwhile; endif; wp_reset_query(); ?> </ul> </div> <?php //首页分类布局开始 $cids = array( 1, 2, 3, 4 ); //这里设置了4个分类ID:1、2、3、4 $len = count($cids); //获取数组长度 for($a=1; $a<=$len; $a++){ //循环获取分类ID $cid = $cids[$a-1]; //当前分类ID ?> <div> <div> <h2><a href="<?php echo get_category_link($cid); ?>"><?php echo get_cat_name($cid); ?></a></h2> <span><a href="<?php echo get_category_link($cid); ?>">更多</a></span> </div> <ul> <?php query_posts( array( 'cat'=> array($cid), 'meta_query' => array( array( 'key' => 'type', 'compare' => 'NOT EXISTS' )), 'showposts' => 10, 'orderby' => 'rand', 'caller_get_posts' => 1, )); //循环输出分类目录文章列表,每个分类调用10篇文章,且不调用带有自定义字段为type的文章; while (have_posts()) : the_post(); echo '<li><a href="'.get_permalink().'" title="'.$post->post_title.'">'.$post->post_title.'</a></li>'; endwhile; wp_reset_query(); ?> </ul> </div> <?php } ?> </div>