WP DEVELOP

EP024. “博客分页与 single.php 美化”

首页 WordPress 开发课程 BLOG · EP024
约 10 分钟· #EP024#BLOG
🔒 登录后可标记已读

继续完善博客部分:先给 /blog 列表加分页链接(用 paginate_links()),再把单篇文章模板 single.php(之前长期没管过,还是最初的裸版本)改成跟其他模板一样有 banner、居中容器,并加上返回博客列表的「Blog Home」链接和 meta 信息(作者/日期/分类)。

涉及文件

  • wp-content/themes/fictional-university-theme/index.php (修改,加一行分页代码)
  • wp-content/themes/fictional-university-theme/single.php (整份重写)

代码实现


index.php(修改:加分页)

在 while 循环结束、外层 container div 关闭之前加一行:

<?php }
  echo paginate_links();
?>

测试分页时可以临时把 设置 → 阅读 → 「博客页面最多显示」 从 10 改成 2,方便用手上仅有的几篇文章看出分页效果,测完记得改回 10

[截图:前台 /blog 列表页底部 paginate_links() 生成的页码链接画面]


single.php(整份重写,之前是最初级的裸模板)

banner 区域和居中容器 class 直接从 page.php 抄过来(因为 single.phppage.php 结构很像),meta box 区域的作者/日期/分类那一段则直接从 index.php 里已经写好的代码复制过来,不用重写:

<?php
  
  get_header();

  while(have_posts()) {
    the_post(); ?>
    <div class="page-banner">
      <div class="page-banner__bg-image" style="background-image: url(<?php echo get_theme_file_uri('/images/ocean.jpg') ?>);"></div>
      <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title"><?php the_title(); ?></h1>
        <div class="page-banner__intro">
          <p>DONT FORGET TO REPLACE ME LATER</p>
        </div>
      </div>  
    </div>

    <div class="container container--narrow page-section">
          <div class="metabox metabox--position-up metabox--with-home-link">
        <p><a class="metabox__blog-home-link" href="<?php echo site_url('/blog'); ?>"><i class="fa fa-home" aria-hidden="true"></i> Blog Home</a> <span class="metabox__main">Posted by <?php the_author_posts_link(); ?> on <?php the_time('n.j.y'); ?> in <?php echo get_the_category_list(', '); ?></span></p>
      </div>

      <div class="generic-content"><?php the_content(); ?></div>

    </div>
    

    
  <?php }

  get_footer();

?>

要点:

  • meta box 原本是 page.php 里那种「返回父页面」的结构(wp_get_post_parent_id() + get_the_title($theParent)),这里把「返回父页面」的逻辑整段去掉,改成写死链接到 site_url('/blog'),文字也从「Back to 父页面标题」改成固定文字「Blog Home」。
  • site_url('/blog') 会返回带域名的绝对路径(而不是相对路径),这样不管在哪个页面点击这个链接都不会出错
  • meta box 里原本准备显示标题(the_title()),改成显示作者/日期/分类那段代码(从 index.php 的 metabox 里复制过来的那一行 Posted by ... on ... in ...)。
  • subtitle 位置暂时留一句「DONT FORGET TO REPLACE ME LATER」占位,这一讲没处理,transcript 里说以后的讲座会处理。

[截图:前台单篇文章页套用重写后的 single.php,含 page-banner 标题、Blog Home 返回链接和作者/日期/分类 meta box 的画面]

Hook / Function 速查

名称类型用途
paginate_links()WP 内建 function(返回值,需要 echo)根据当前查询自动生成上一页/下一页/页码链接
site_url($path)WP 内建 function(返回值,需要 echo)返回带域名的绝对 URL,$path 是要拼在域名后面的路径

常见坑

  • paginate_links()get_the_category_list() 一样是返回值型函数,必须 echo 才会显示,不加会看起来像没生效。
  • 测试分页效果时如果博客文章数量不够(这门课当时只有 4 篇),需要临时把「博客页面最多显示」调小(比如调成 2)才能看到分页链接,测完别忘了改回默认的 10,否则线上博客一页只显示 2 篇

延伸 / 后续讲座会用到

  • single.php 的 subtitle 占位文字(「DONT FORGET TO REPLACE ME LATER」)会在后续讲座补上。
  • 作者链接和分类链接点进去是归档页,目前还是用 index.php 顶替,归档标题问题在 EP025 处理。

Sources

Udemy:

  • Become a WordPress Developer: Unlocking Power With Code — Section 6, EP024