为WordPress作者简介社交链接添加条件渲染逻辑
解决方案
需求说明
已为作者简介实现社交链接功能,需添加条件逻辑:当作者填写了Facebook或Twitter社交链接时,才生成带有social-area social-area-2类的<ul>标签;若未填写任何社交链接,则不生成该标签。
修改后的代码文件
author-bio.php
<?php $facebook = get_the_author_meta('facebook', $author_id); $twitter = get_the_author_meta('twitter', $author_id); if ( (bool) get_the_author_meta( 'description' ) && (bool) get_theme_mod( 'show_author_bio', true ) ) : ?> <div class="author-area"> <div class="media"> <?php echo get_avatar( get_the_author_meta( 'ID' ), 120 ); ?> <div class="media-body align-self-center"> <div class="text-author"> <h4> <a class="author-link" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"> <?php printf(get_the_author() ); ?> </a> </h4> <?php echo wp_kses_post( wpautop( get_the_author_meta( 'description' ) ) ); ?> </div> <?php // 判断是否存在至少一个有效社交链接 if ( !empty($facebook) || !empty($twitter) ) : ?> <ul class="social-area social-area-2"> <?php if(!empty($facebook)) { echo '<li><a title="Follow me on Facebook" href="'.$facebook.'"><i class="fab fa-facebook-f"></i></a></li>'; } ?> <?php if(!empty($twitter)) { echo '<li><a title="Follow me on Twitter" href="'.$twitter.'"><i class="fab fa-twitter"></i></a></li>'; } ?> </ul> <?php endif; ?> </div> </div> </div> <?php endif; ?>
functions.php(无需修改,保留原代码)
function my_new_contactmethods( $contactmethods ) { $contactmethods['facebook'] = 'Facebook'; $contactmethods['twitter'] = 'Twitter'; return $contactmethods; } add_filter('user_contactmethods','my_new_contactmethods',10,1);
修改要点
- 在原代码的社交列表容器
<ul>外层新增条件判断if ( !empty($facebook) || !empty($twitter) ) :,仅当Facebook或Twitter链接至少有一个不为空时,才渲染该列表标签。 - 添加对应的闭合语句
<?php endif; ?>,确保条件代码块正确闭合。
内容的提问来源于stack exchange,提问作者Moinds
相关产品推荐
相关产品推荐

