PHP+Genesis Simple Hooks多分类文章重复显示头部问题求助
多分类文章重复头部问题解决方案
问题说明
使用PHP和Genesis Simple Hooks为不同分类文章分配头部时,单分类文章显示正常,但文章被分配多个分类(如同时属于news和podcast-season-4)时,页面会加载多个头部。需要实现规则:当文章同时包含这两个分类时,不显示news对应的头部。
原代码(导致重复头部)
STRING ONE
<?php $post = $wp_query->post; if ( in_category ( array ( 'news' , 'featured-news' ) ) ) { echo '<div class="wrap"><div class="entry-content"> <h1 class="wp-block-heading graya"><a href="https://baker.utk.edu/news-and-events/news-archive/">News</a></h1> </div></div> '; } ?>
STRING TWO
<?php $post = $wp_query->post; if ( in_category ( array ( 'podcast-season-4' ) ) ) { echo '<div class="wrap"><div class="entry-content"><a href="https://baker.utk.edu/news-and-events/podcast/"><div class="wp-block-cover__inner-container is-layout-flow wp-block-cover-is-layout-flow"> <figure class="wp-block-image alignleft size-large is-resized podcast-icon" ><img decoding="async" src="https://baker.utk.edu/wp-content/uploads/2024/02/YMBR.Logo_.Smokey.Slant_.svg" alt="You Might Be Right Logo" class="wp-image-8490" style="width:90px;height:auto"></figure></a> <h1 class="wp-block-heading graya"><a href="https://baker.utk.edu/news-and-events/podcast/">Podcast</a></h1> </div></div></div> '; } ?>
修改后的代码方案
将两个逻辑整合,优先判断高优先级分类,避免重复输出:
<?php $post = $wp_query->post; // 优先处理podcast-season-4分类,满足则输出播客头部 if (in_category('podcast-season-4')) { echo '<div class="wrap"><div class="entry-content"><a href="https://baker.utk.edu/news-and-events/podcast/"><div class="wp-block-cover__inner-container is-layout-flow wp-block-cover-is-layout-flow"> <figure class="wp-block-image alignleft size-large is-resized podcast-icon" ><img decoding="async" src="https://baker.utk.edu/wp-content/uploads/2024/02/YMBR.Logo_.Smokey.Slant_.svg" alt="You Might Be Right Logo" class="wp-image-8490" style="width:90px;height:auto"></figure></a> <h1 class="wp-block-heading graya"><a href="https://baker.utk.edu/news-and-events/podcast/">Podcast</a></h1> </div></div></div>'; } // 仅当文章不属于podcast-season-4时,才判断是否输出news头部 elseif (in_category(array('news', 'featured-news'))) { echo '<div class="wrap"><div class="entry-content"> <h1 class="wp-block-heading graya"><a href="https://baker.utk.edu/news-and-events/news-archive/">News</a></h1> </div></div>'; } ?>
逻辑说明
- 用
elseif替代独立if,确保同一时间只会触发一个头部输出逻辑 - 给
news分类的判断添加排他条件:只有当文章不属于podcast-season-4时,才会输出新闻头部 - 优先处理
podcast-season-4分类,保证多分类场景下只显示高优先级的头部
内容的提问来源于stack exchange,提问作者Jill Knight
相关产品推荐
相关产品推荐

