如何使用WordPress的the_excerpt() 和 the_content() 函数显示文章摘要和全文?

2025-01-09 71 0

在WordPress中,the_excerpt()the_content() 是两个常用的模板函数,用于显示文章的摘要和全文。以下是如何使用这两个函数的步骤:

使用 the_excerpt() 显示文章摘要

  1. 确保摘要功能已启用
    在WordPress的设置中,确保“手动摘要”选项被选中。这可以通过以下步骤完成:

    • 登录到WordPress管理后台。
    • 转到“设置” > “撰写”。
    • 在“摘要”部分,选择“手动摘要”。
  2. 在文章编辑器中输入摘要
    当你创建或编辑一篇文章时,在文章编辑器下方有一个“摘要”框,你可以在这里输入文章的摘要。

  3. 在模板文件中使用 the_excerpt()
    在你的主题的模板文件中(通常是 index.phparchive.phpsearch.php 等),使用 the_excerpt() 函数来显示文章摘要。

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
       <h2><?php the_title(); ?></h2>
       <?php the_excerpt(); ?>
       <a href="<?php the_permalink(); ?>">阅读更多</a>
    <?php endwhile; endif; ?>

使用 the_content() 显示文章全文

  1. 在模板文件中使用 the_content()
    在你的主题的模板文件中(通常是 single.phppage.php 等),使用 the_content() 函数来显示文章的全文。

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
       <h2><?php the_title(); ?></h2>
       <?php the_content(); ?>
    <?php endwhile; endif; ?>
  2. 可选:添加“阅读更多”链接
    如果你想要在摘要后添加一个“阅读更多”链接,可以在 the_excerpt() 后面添加一个链接到文章的永久链接。

    <a href="<?php the_permalink(); ?>">阅读更多</a>
  3. 自动分页
    如果文章很长,the_content() 会自动处理分页,如果你想要自定义分页链接,可以使用 the_content() 的分页参数。

    <?php the_content( 'Continue reading <span class="meta-nav">&rarr;</span>' ); ?>

记住,the_excerpt() 通常用于文章列表页面,而 the_content() 用于显示单个文章或页面的完整内容。根据你的需求,你可以在不同的模板文件中使用这些函数。

相关文章

如何在WordPress插件中使用ajax?
如何通过WordPress函数创建自定义菜单?
在WordPress主题开发中,如何使用WP_Customize_Manager来自定义主题选项?
如何使用WordPress的filter钩子修改输出内容?
如何使用WordPress的action钩子添加自定义JavaScript?
在WordPress插件中,如何使用自定义表单和nonce字段来增强安全性?