如何在WordPress动态菜单标签中添加静态「全部」标签展示所有文章
修改后完整实现代码
PHP 部分
<?php echo '<ul class="nav nav-tabs" role="tablist">'; // 先添加「全部」静态标签 echo '<li> <span data-href="all" role="tab" data-toggle="tab"> 全部 </span> </li>'; $args = array( 'taxonomy' => 'annualreports_category', 'hide_empty'=>0, 'orderby' => 'name', 'order' => 'ASC' ); $categories = get_categories($args); foreach($categories as $category) { echo '<li> <span data-href="'.$category->slug.'" role="tab" data-toggle="tab"> '.$category->name.' </span> </li>'; } echo '</ul>'; echo '<div class="investors-content">'; // 先添加「全部」对应的内容面板 echo '<div class="tab-pane" id="all">'; $all_query = new WP_Query(array( 'post_type' => 'annualreports_post', 'posts_per_page' => -1, )); while ( $all_query->have_posts() ) : $all_query->the_post(); echo '<h1>'; the_title(); echo '</h1>'; endwhile; wp_reset_postdata(); // 重置查询避免后续查询异常 echo '</div>'; // 原有分类内容面板逻辑不变 foreach($categories as $category) { echo '<div class="tab-pane" id="' . $category->slug.'">'; $catslug = $category->slug; $the_query = new WP_Query(array( 'post_type' => 'annualreports_post', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'annualreports_category', 'field' => 'slug', 'terms' => array( $catslug ), 'operator' => 'IN' ), ), )); while ( $the_query->have_posts() ) : $the_query->the_post(); echo '<h1>'; the_title(); echo '</h1>'; endwhile; wp_reset_postdata(); echo '</div>'; } echo '</div>'; ?>
JS 部分
$(".investors-content .tab-pane").each(function(){ $(this).hide(); // 默认显示「全部」面板,要默认显示第一个分类可替换为 .tab-pane:eq(1) $('.investors-content .tab-pane:first').show(); }); $('.nav-tabs li>span').on( "click", function(e) { e.preventDefault(); var id = $(this).attr('data-href'); $(".investors-content .tab-pane").each(function(){ if(id === 'all'){ // 点击全部时展示所有面板 $(this).show(); }else{ // 普通分类点击逻辑不变 $(this).hide(); if($(this).attr('id') == id) { $(this).show(); } } }); });
内容的提问来源于stack exchange,提问作者Roberto
相关产品推荐
相关产品推荐

