TwentyTwentyOne子主题:让自定义Logo在首页也链接至首页
解决TwentyTwentyOne子主题首页Logo无跳转链接的问题
原因分析
TwentyTwentyOne父主题默认会移除首页Logo的跳转链接,这个逻辑并非写在site-branding.php模板中,而是通过主题过滤器(Filter)实现的,所以你在模板文件里看不到相关判断代码。
解决方案
方案一:通过过滤器恢复首页Logo链接
在子主题的functions.php文件中添加以下代码,直接取消父主题移除链接的逻辑:
add_filter( 'twenty_twenty_one_custom_logo_attributes', '__return_empty_array' );
如果需要精准控制(仅首页保留链接),可使用这段代码:
add_filter( 'twenty_twenty_one_custom_logo_attributes', function( $attributes ) { if ( is_front_page() ) { unset( $attributes['href'] ); } return $attributes; } );
方案二:重写模板文件强制添加链接
- 复制父主题目录下的
template-parts/header/site-branding.php文件,粘贴到子主题的template-parts/header/目录中 - 修改文件代码,将
the_custom_logo()用首页链接标签包裹:
<?php if ( has_custom_logo() && $show_title ) : ?> <div class="site-logo"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"> <?php the_custom_logo(); ?> </a> </div> <?php endif; ?> <div class="site-branding"> <?php if ( has_custom_logo() && ! $show_title ) : ?> <div class="site-logo"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"> <?php the_custom_logo(); ?> </a> </div> <?php endif; ?>
验证修改
保存代码后刷新首页,点击Logo即可跳转至首页。
内容的提问来源于stack exchange,提问作者dstN
相关产品推荐
相关产品推荐

