腾讯云服务器优惠活动华纳云香港服务器

如何纯代码实现在WordPress文章末尾添加一个作者信息框?

WordPress主题推荐

前面 boke112 联盟跟大家分享过通过安装 Simple Author Box 插件可以轻松实现在 WordPress 文章末尾添加一个响应式作者信息框,但是有些站长不喜欢插件而喜欢纯代码实现,那么应该如何实现呢?其实只需要简单两步即可。

第一步:将以下代码添加到当前主题 functions.php 中即可。

function wp_author_info_box( $content ) {
global $post;
// 检测文章与文章作者
if ( is_single() && isset( $post->post_author ) ) {
// 获取作者名称
$display_name = get_the_author_meta( 'display_name', $post->post_author );
// 如果没有名称,使用昵称
if ( empty( $display_name ) )
$display_name = get_the_author_meta( 'nickname', $post->post_author );
// 作者的个人信息
$user_description = get_the_author_meta( 'user_description', $post->post_author );
// 获取作者的网站
$user_website = get_the_author_meta('url', $post->post_author);
// 作者存档页面链接
$user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author));
if ( ! empty( $display_name ) )
$author_details = '<div class="author-name">关于 ' . $display_name . '</div>';
if ( ! empty( $user_description ) )
// 作者头像
$author_details .= '<div class="author-details">' . get_avatar( get_the_author_meta('user_email') , 90 ) . nl2br( $user_description ). '</div>';
$author_details .= '<div class="author-links"><a href="'. $user_posts .'">查看 ' . $display_name . ' 所有文章</a>';
// 检查作者在个人资料中是否填写了网站
if ( ! empty( $user_website ) ) {
// 显示作者的网站链接
$author_details .= ' | <a href="' . $user_website .'" target="_blank" rel="nofollow">网站</a></div>';
} else {
// 如果作者没有填写网站则不显示网站链接
$author_details .= '</div>';
}
// 在文章后面添加作者信息
$content = $content . '<footer class="author-bio-section" >' . $author_details . '</footer>';
}
return $content;
}
// 添加过滤器
add_action( 'the_content', 'wp_author_info_box' );
// 允许 HTML
remove_filter('pre_user_description', 'wp_filter_kses');

第二步:将以下 CSS 代码添加到当前主题的 style.css 文件中。

.author-bio-section {
background: #fff;
float: left;
width: 100%;
margin: 10px 0;
padding: 15px;
border: 1px dashed #ccc;
}
.author-name {
font-size: 15px;
font-weight: bold;
margin: 0 0 5px 0;
}
.author-details img {
float: left;
width: 48px;
height: auto;
margin: 5px 15px 0 0;
}

以上代码来自@知更鸟WPBeginner

最终效果如下图所示:

如何纯代码实现在WordPress文章末尾添加一个作者信息框?-第1张-boke112百科(boke112.com)

而关于作者信息的编辑可以进入 WordPress 后台 – 用户 – 个人资料进入相应页面修改。

本文地址:https://boke112.com/post/7384.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu