我们在自己建网站
时,经过碰到网站上的不同页面的边栏是显示各自栏目下的子栏目或者子页面。如果每个都去单独写的话比较麻烦,为了简洁代码,我们可以使用Wordpress的判断来显示。
Wordpress不同页面调用子栏目代码判断写法如下:<?php if(is_category()){?>
<h3><?php echo get_cat_name( get_category_root_id($cat) );?></h3>
<ul>
<?php
$args=array(
child_of=> get_category_root_id($cat),
hide_empty=>0,
);
$categories=get_categories($args);
foreach($categories as $category) {
echo <li><a href=" . get_category_link( $category->term_id ) . " class="lis"> . $category->name.</a></li>;
}
?>
</ul>
<?php }elseif(is_single()){?>
<?php $currecategory =get_the_category();$djcatid = get_category_root_id($currecategory[0]->cat_ID);?>
<h3><?php echo get_cat_name( $djcatid );?></h3>
<ul>
<?php
$args=array(
child_of=> $djcatid,
hide_empty=>0,
);
$categories=get_categories($args);
foreach($categories as $category) {
echo <li><a href=" . get_category_link( $category->term_id ) . " class="lis"> . $category->name.</a></li>;
}
?>
</ul>
<?php }elseif(is_page()){?>
<h3><?php wp_title();?></h3>
<ul>
<?php
$pageArray = get_post_ancestors($post->ID);//获取父页面ID
if($pageArray){
$pageid = $pageArray[0];
}else{
$pageid = $post->ID;
}
$pages = get_pages(child_of=.$pageid.&sort_column=post_date&sort_order=desc&parent=.$pageid);
if($pages){
foreach($pages as $page){
echo <li><a href=" . get_page_link($page->ID) . " class="lis"> . $page->post_title.</a></li>;
}
}else{
$pagesr = get_pages();
foreach ($pagesr as $paggr) {
echo <li><a href=" .get_page_link($paggr->ID). " class="lis"> . $paggr->post_title. </a></li>;
}
}
?>
</ul>
<?php }else{?>
<h3>栏目导航</h3>
<ul>
<?php
$args=array(
orderby => ID,
order => ASC,
);
$categories=get_categories($args);
$kk=1;
foreach($categories as $category) {
echo <li><a href=" . get_category_link( $category->term_id ) . " class="lis" > . $category->name.</a></li>;
$kk++;
if($kk>6)
break;
}
?>
</ul>
<?php }?>
把上面的代码保存成sidebar.php,可以在任何页面调用这个PHP文件来自动判断显示边栏导航了。
标签: