獲取文章頁面上級目錄或下級目錄時會用到下面的程序了,下面我分別與各位同學一看看調用上下級分類目錄程序代碼.在當前分類或者正文頁面想調用顯示與當前分類存在父子關系的分類目錄時會用到.
代碼一:將下面代碼加到主題模板適當位置,比如側邊欄:
- <?php
- $current = "";
- if(is_single()){
- $parent = get_the_category();
- $parent = $parent[0];
- $current = "¤t_category=".$parent->term_id;
- }else if(is_category()){
- global $cat;
- $parent = get_category($cat);
- }
- if($parent->category_parent != 0){
- $cat_id = $parent->category_parent;
- $parent = get_category($cat_id);
- if($parent->category_parent != 0){
- $cat_id = $parent->category_parent;
- }else{
- $cat_id = $parent->term_id;
- }
- }else{
- $cat_id = $parent->term_id;
- }
- ?>
- <?php if(!is_page()) { ?>
- <h3><?php echo $parent->cat_name; ?><span><?php echo $parent->slug; ?></span></h3>
- <ul id="cat_list">
- <?php wp_list_categories("title_li=&child_of=$cat_id".$current); ?>
- </ul>
- <?php } ?>
代碼二:將下面代碼加到主題function.php模板文件中:
- function get_category_root_id($cat)
- {
- $this_category = get_category($cat); // 取得當前分類
- while($this_category->category_parent) // 若當前分類有上級分類時,循環
- {
- $this_category = get_category($this_category->category_parent); // 將當前分類設為上級分類(往上爬)
- }
- return $this_category->term_id; // 返回根分類的id號
- }
調用顯示代碼加到主題模板的適當位置,代碼如下:
- <?php
- if(is_category())
- {
- if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" )
- {
- echo '<ul>';
- 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");
- echo '</ul>';
- }
- }
- ?>
如果我們要調用當前目錄下文章怎么調用?在想要調用分類最新文章列表的地方添加以下代碼:
- <?php
- query_posts('showposts=1&cat=3');
- while(have_posts()) : the_post();
- ?>
- <ul>
- <li><h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
- <ul><li><?php the_content(); ?></li>
- </ul>
- </li>
- </ul>
- <?php endwhile; ?>
其中showposts后面的數碼表示顯示的文章數量,cat后面的數值表示分類ID,調用wordpress指定文章,代碼如下:
- <?php query_posts('p=1'); ?>
- <?php while (have_posts()) : the_post(); ?>
- <a href="<?php the_permalink(); ?>"><?php the_content(); ?></a>
- <?php endwhile;wp_reset_query();?>
新聞熱點
疑難解答
圖片精選