小冬SEO

wordpress调用指定分类或当前分类的子分类

2021-11-09 23:09:24 12230 WordPress笔记

很多时候我们创建很多二级子分类,或者三级子分类,这个时候我们就需要调用这些指定的分类,你们可以用到下面的代码来实现想要的调用方式,尤其是第三种,是我常用的调用,二级分类和三级分类同时存在的时候,需要调用所有的二级分类和当前二级分类下的三级分类,这样才符合我们的浏览体验。

1.调用指定分类下的子分类

//a
<?php
$categories=get_categories("child_of=1");
  foreach($categories as $category) {
	echo '<li class="liebiao"><a href="'.get_category_link( $category->term_id ).'">'.$category->name.'</a></li>';
  }
?>
//b
<?php $args=array('child_of'=> '2','hide_empty'=>'0',);$categories=get_categories($args);foreach($categories as $category) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "%s" ), $category->name ) . '" ' . '>' . $category->name.'</a></li>';
}
?>
//c
<?php wp_list_cats("child_of=2&depth=1&hierarchical=1&hide_empty=0");?>

2.循环调用多个分类列表

<?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 class="index_3 row">
<h2>
<a href="<?php echo get_category_link($cid); ?>"><?php echo get_cat_name($cid); ?></a>
<span><a href="<?php echo get_category_link($cid); ?>">更多</a></span>
</h2>
<div class="index_3_top">
<div class="left">
<?php
query_posts('posts_per_page=4&caller_get_posts=1&orderby=modified&cat='.$cid);
while (have_posts()) : the_post();
echo '<a target="_blank" href="'.get_permalink().'" class="title" title="'.$post->post_title.'">';
if (has_post_thumbnail()) { //如果缩略图存在,就调用缩略图
the_post_thumbnail( 'thumbnail',array( 'alt' => trim(strip_tags( $post->post_title )), 'class' => 'home-thumb'));
}else { //如果缩略图不存在,就调用catch_first_image()方法获取第一张图或默认图
echo '<img src="'.catch_first_image().'" alt="'.$post->post_title.'" />';
}
echo '<h3>'.$post->post_title.'</h3>';
echo '</a>';
endwhile;
wp_reset_query();
?>
</div>
<div class="center">
<?php
query_posts('posts_per_page=12&caller_get_posts=1&orderby=rand&cat='.$cid);
while (have_posts()) : the_post();
echo '<a target="_blank" href="'.get_permalink().'" class="title" title="'.$post->post_title.'">'.$post->post_title.'</a>';
endwhile;
wp_reset_query();
?>
</div>
</div>
</div>
<?php } ?>

3.调用当前分类下的所有子分类

这个调用代码跟调用指定分类下的子分类不一样。

<?php
  if(is_single()||is_category()){
      if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" ){
          echo wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=&orderby=id&order=ASC");
      }
  }
?>

版权保护: 本文由小冬SEO编辑发布,转载请保留链接: http://www.myseoyh.cn/shuo/158.html