外贸营销

WordPress主题开发中获取指定分类下所有子分类名称及文章列表
2019.09.06 外贸营销

我们在WordPress主题开发过程中,有的时候会需要做一个文章聚合页,比如显示所有新闻分类下二级新闻分类的名称及文章列表,如下图:

WordPress主题开发中获取指定分类下所有子分类名称及文章列表

那么要实现这一的效果,就可以用类似下面的代码就可以了:

<?phpglobal $cat;$cats = get_categories(array('child_of' => $cat,'parent' => $cat,'hide_empty' => 0));$c = get_category($cat);if(empty($cats)){?><div class="item"><?php if (have_posts()) : while (have_posts()) : the_post(); ?><div class="post"><h2><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2><p><?php the_excerpt(); ?></p><p><a href="<?php the_permalink(); ?>">more >></a></p><div class="meta"><?php the_time('Y-m-d'); ?> | 标签: <?php the_tags('', ' , ', ''); ?></div></div><?php endwhile; ?><?php else: ?><div class="post"><p>暂无文章</p></div><?php endif; ?></div><div class="navigation"><span class="alignleft"><?php next_posts_link('&laquo; Older posts') ?></span><span class="alignright"><?php previous_posts_link('Newer posts &raquo;') ?></span></div><?php}else{foreach($cats as $the_cat){$posts = get_posts(array('category' => $the_cat->cat_ID,'numberposts' => 10,));if(!empty($posts)){echo '<div class="item cat_item"><div class="item_title"><h2><a title="'.$the_cat->name.'" href="'.get_category_link($the_cat).'">'.$the_cat->name.'</a></h2></div><ul class="box_list">';foreach($posts as $post){echo '<li><span class="alignright">'.mysql2date('Y-m-d', $post->post_date).'</span><a title="'.$post->post_title.'" href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';}echo '</ul></div>';}}}?>

也就是首先我们需要判断一下当前分类包含的二级子分类,然后调用出所有的二级分类ID,再通过ID去调用子分类的名称和子分类下面的文章列表。

上一篇下一篇
标签

有问
必答