PHP代码判断WordPress不同页面调用边栏导航
我们在自己建网站时,经过碰到网站上的不同页面的边栏是显示各自栏目下的子栏目或者子页面。如果每个都去单独写的话比较麻烦,为了简洁代码,我们可以使用Wordpress的判断来显示。
Wordpress不同页面调用子栏目代码判断写法如下:
<style>span.nossy{display:none;}</style>
<?php if(is_category()){?>
<h3><?php echo get_cat_name( get_category_root_id($cat) );?><span class="nossy"><?php $mycat = get_category(get_category_root_id($cat));echo strtoupper($mycat->slug);?></span></h3>
<ul>
<?php
$args=array(
'child_of'=> get_category_root_id($cat),
'parent' => get_category_root_id($cat),
'hide_empty'=>'0',
);
$categories=get_categories($args);
foreach($categories as $category) {
if($cat == $category->term_id){$ons='actions';}else{$ons='';}
echo '<li><a href="' . get_category_link( $category->term_id ) . '" class="lis '.$ons.'">' . $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 );?><span class="nossy"><?php $mycat = get_category($djcatid);echo strtoupper($mycat->slug);?></span></h3>
<ul>
<?php
$args=array(
'child_of'=> $djcatid,
'parent' => $djcatid,
'hide_empty'=>'0',
);
$categories=get_categories($args);
foreach($categories as $category) {
if($currecategory[0]->cat_ID == $category->term_id){$ons='actions';}else{$ons='';}
echo '<li><a href="' . get_category_link( $category->term_id ) . '" class="lis '.$ons.'">' . $category->name.'</a></li>';
}
?>
</ul>
<?php }elseif(is_page()){
$pageArray = get_post_ancestors($post->ID);//获取父页面ID
if($pageArray){
$pageid = $pageArray[0];
}else{
$pageid = $post->ID;
}?>
<h3><?php echo get_page($pageid)->post_title;?><span class="nossy"><?php $slug = get_page( $pageid ); echo strtoupper($slug->post_name);?></span></h3>
<ul>
<?php
$pages = get_pages('child_of='.$pageid.'&sort_column=menu_order&sort_order=desc&parent='.$pageid);
if($pages){
foreach($pages as $page){
if($post->ID == $page->ID){$ons='actions';}else{$ons='';}
echo '<li><a href="' . get_page_link($page->ID) . '" class="lis '.$ons.'">' . $page->post_title.'</a></li>';
}
}else{
$pagesr = get_pages();
foreach ($pagesr as $paggr) {
if($post->ID == $page->ID){$ons='actions';}else{$ons='';}
echo '<li><a href="' . get_page_link($paggr->ID). '" class="lis '.$ons.'">' . $paggr->post_title. '</a></li>';
}
}
?>
</ul>
<?php }else{?>
<h3>栏目导航<span class="nossy">MEAU</span></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文件来自动判断显示边栏导航了。