利用echo=0判断页面是否存在子页面
| Category:
Wordpress |
No Comments
当本页面存在父页面时,在sidebar列出父页面下属的所有页面(即列出跟本页面同级的页面),当本页面为父页面时,则列本页的子页面出来,这是CMS最普遍的应用之一,实现方法为(sidebar.php):
- <?php if (have_posts()) : ?>
- <?php while (have_posts()) : the_post(); ?>
- <?php /* Creates a menu for pages beneath the level of the current page - Thanks K2 Theme*/
- if (is_page() and ($notfound != '1')) {
- $parent_page = $post->ID;
- while($parent_page) {
- $page_query = $wpdb->get_row("SELECT ID, post_title, post_status, post_parent FROM $wpdb->posts WHERE ID = '$parent_page'");
- $parent_page = $page_query->post_parent;
- }
- $parent_id = $page_query->ID;
- $parent_title = $page_query->post_title;
- if ($wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = '$parent_id' AND post_status != 'attachment'")) { ?>
- <div class="s_panel">
- <h2 class="title"><?php echo $parent_title; ?></h2>
- <ul><?php wp_list_pages('depth=1&sort_column=menu_order&title_li=&child_of='. $parent_id); ?></ul>
- </div>
- <?php }?>
- <?php } } ?>
- <?php endwhile; endif; ?>
但是有个问题一直没解决,就是当本页面是很孤独的页面,没有父页面也没有子页面时,怎样让侧边不出现这个s_panel,以前我用两种作法,一是硬挤几个同级页面给它,一是做2个template,带和不带s_panel各一个,都很麻烦,刚突然发现了可以在上述parent_id功能上,再利用wp_list_pages结合echo=0来判断是否要输出,问题就迎刃而解了。真是好晕,整天在CODEX上的wp_list_pages上琢磨,却完全没有看到echo=0!
改后的代码如下:
- <?php if (have_posts()) : ?>
- <?php while (have_posts()) : the_post(); ?>
- <?php /* Creates a menu for pages beneath the level of the current page - Thanks K2 Theme*/
- if (is_page() and ($notfound != '1')) {
- $parent_page = $post->ID;
- while($parent_page) {
- $page_query = $wpdb->get_row("SELECT ID, post_title, post_status, post_parent FROM $wpdb->posts WHERE ID = '$parent_page'");
- $parent_page = $page_query->post_parent;
- }
- $parent_id = $page_query->ID;
- $parent_title = $page_query->post_title;
- if ($wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = '$parent_id' AND post_status != 'attachment'")) { ?>
- <?php $subpage = wp_list_pages('depth=1&echo=0&child_of='.$parent_id); ?><?php //关键 ?>
- <?php if($subpage) { ?>
- <div class="s_panel">
- <h2 class="title"><?php echo $parent_title; ?></h2>
- <ul><?php wp_list_pages('depth=1&sort_column=menu_order&title_li=&child_of='. $parent_id); ?></ul>
- </div>
- <?php }?>
- <?php } } ?>
- <?php endwhile; endif; ?>
今天顺便把WP升级到2.7了,进入后台却发现侧栏导航条不见了,冷静的思考一下,怀疑是插件lighter-menu导致的,直接在地址栏输入插件页将之停用,马上恢复正常!:)
Tag: subpage, Wordpress, wp_list_pages