在WordPress 文章未尾自动添加一个作者信息框

2019年6月3日14:33:13 发表评论 1,555 views

在WordPress 文章未尾自动添加一个作者信息框

如果想在WordPress文章的末尾,添加文章作者的相关信息,下面一段代码可以方便在文章中添加一个作者的信息框。

将代码添加到当前主题functions.php中:

  1. function wp_author_info_box( $content ) {
  2.     global $post;
  3.     // 检测文章与文章作者
  4.     if ( is_single() && isset( $post->post_author ) ) {
  5.         // 获取作者名称
  6.         $display_name = get_the_author_meta( 'display_name', $post->post_author );
  7.         // 如果没有名称,使用昵称
  8.         if ( empty$display_name ) )
  9.         $display_name = get_the_author_meta( 'nickname', $post->post_author );
  10.         // 作者的个人信息
  11.         $user_description = get_the_author_meta( 'user_description', $post->post_author );
  12.         // 获取作者的网站
  13.         $user_website = get_the_author_meta('url', $post->post_author);
  14.         // 作者存档页面链接
  15.         $user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author));
  16.         if ( ! empty$display_name ) )
  17.         $author_details = '<div class="author-name">关于 ' . $display_name . '</div>';
  18.         if ( ! empty$user_description ) )
  19.         // 作者头像
  20.         $author_details .= '<div class="author-details">' . get_avatar( get_the_author_meta('user_email') , 90 ) . nl2br$user_description ). '</div>';
  21.         $author_details .= '<div class="author-links"><a href="'. $user_posts .'">查看 ' . $display_name . ' 所有文章</a>';
  22.         // 检查作者在个人资料中是否填写了网站
  23.         if ( ! empty$user_website ) ) {
  24.         // 显示作者的网站链接
  25.         $author_details .= ' | <a href="' . $user_website .'" target="_blank" rel="nofollow">网站</a></div>';
  26.         } else {
  27.             // 如果作者没有填写网站则不显示网站链接
  28.             $author_details .= '</div>';
  29.         }
  30.         // 在文章后面添加作者信息
  31.         $content = $content . '<footer class="author-bio-section" >' . $author_details . '</footer>';
  32.     }
  33.     return $content;
  34. }
  35. // 添加过滤器
  36. add_action( 'the_content', 'wp_author_info_box' );
  37. // 允许HTML
  38. remove_filter('pre_user_description', 'wp_filter_kses');

再将配套的CSS添加到主题样式文件style.css中:

  1. .author-bio-section {
  2.     background#fff;
  3.     floatleft;
  4.     width: 100%;
  5.     margin10px 0;
  6.     padding15px;
  7.     border1px dashed #ccc;
  8. }
  9. .author-name {
  10.     font-size15px;
  11.     font-weightbold;
  12.     margin: 0 0 5px 0;
  13. }
  14. .author-details img {
  15.     floatleft;
  16.     width48px;
  17.     heightauto;
  18.     margin5px 15px 0 0;
  19. }

最终效果:在WordPress 文章未尾自动添加一个作者信息框源代码:http://www.wpbeginner.com/wp-tutorials/how-to-add-an-author-info-box-in-wordpress-posts/

站长小智

发表评论

您必须登录才能发表评论!