WordPress利用wp_list_pages显示页面目录

这几天玩博客发现wordpress自带的导航栏对子页面的显示很不友好,默认是所有子页面都在导航栏显示。但是我想让子页面以下拉条式的样子显示。

在网上找了很多方法,有的多把日志分类放在导航条上就行了,但是日志一般会写很多,放在导航栏很不妥。

有人推荐用插件,像我这种最不喜欢依赖插件的人当然是选择能用代码就用代码解决了。虽然不美观,但是没有累赘。

于是我找了一个折中的办法,导航栏上不显示子页面,在所有主页面、子页面里显示页面树。

主页面会显示全部目录,子页面只显示子目录和父页面地址。

具体效果请见本博客的photos一栏。

参考了官方文档:http://codex.wordpress.org/Function_Reference/wp_list_pages

以下是我自己参考官方文档写的代码。把这段代码加到page.php的合适位置就行,我是加在the_content内容之下,也就是page内容之下。

之前没接触过php,不过凭我c的经验还是很好写这东西,发现他既具有lua的特点也具有c的特点。

这段代码会在所有主页面以及子页面里显示该文档的整体结构。网上的一些代码无法追溯到最顶级页面,感觉不友好。

<!--子页面分类显示begin--->
<?php
  if ($post->post_parent)
 $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&link_before=>>"); 
  else
 $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&link_before=>>");
 
  if ($children) { ?>
<div style="border:1px dashed #ddd; padding:10px; margin:10px 0;line-height:26px;border-radius: 3px;"><div>
  <?php
  if ($post->post_parent)
   echo '<h2>父窗口:' . "<a href=" . get_permalink( $post->post_parent ) . ">" .
   get_the_title($post->post_parent) . '</a></h2>';
  else
   echo '<h2>'.get_the_title($post->ID).'目录:</h2>';
  ?>
  <ul>
  <?php echo $children; ?>
  </ul>
</div>
<?php } ?>
<!--子页面分类显示end--->

如果有的模板使用上面的代码后显示错位,有可能是上面的边框把模板顶错位了,解决办法,删掉

<div style="border:1px dashed #ddd; padding:10px; margin:10px 0;line-height:26px;border-radius: 3px;"><div>

以及下面对应的

</div>

让导航栏不显示子页面的方法:
找到header.php代码中的

<?php wp_list_pages('title_li=&depth=-1'); ?>

改为

<?php wp_list_pages('title_li=&depth=1'); ?>

原创内容,转载请一并复制下面的版权地址,请尊重别人的劳动成果,谢谢。

留下只言片语: