在WordPress中,the_excerpt()
和 the_content()
是两个常用的模板函数,用于显示文章的摘要和全文。以下是如何使用这两个函数的步骤:
使用 the_excerpt()
显示文章摘要
-
确保摘要功能已启用:
在WordPress中,默认情况下,文章摘要功能是启用的。如果需要,可以在后台的“设置” > “撰写”中查看和调整摘要设置。 -
在主题文件中调用
the_excerpt()
:
在你的主题的模板文件中(通常是index.php
、archive.php
、search.php
或home.php
),你可以使用the_excerpt()
函数来显示文章的摘要。例如,在
index.php
文件中,你可能会有如下代码:<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <a href="<?php the_permalink(); ?>" class="more-link">阅读更多</a> </article> <?php endwhile; endif; ?>
这段代码会在循环中显示每个文章的标题、摘要和一个“阅读更多”的链接。
使用 the_content()
显示文章全文
-
在主题文件中调用
the_content()
:
当你想要显示单篇文章的全文时,你需要在单篇文章模板文件中(通常是single.php
)使用the_content()
函数。例如,在
single.php
文件中,你可能会有如下代码:<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2 class="entry-title"><?php the_title(); ?></h2> <?php the_content(); ?> </article> <?php endwhile; endif; ?>
这段代码会在单篇文章页面中显示文章的标题和全文。
注意事项
the_excerpt()
显示的是文章摘要,通常是从文章内容的前55个单词自动生成的,或者是由作者在编辑文章时手动指定的。the_content()
显示的是文章的完整内容,包括所有的格式和短代码。- 如果你想自定义摘要的长度,可以使用
excerpt_length
过滤器来调整摘要的单词数量。 - 如果你想自定义摘要的结束文本(默认是 " [...]"),可以使用
excerpt_more
过滤器。
以下是一个自定义摘要长度和结束文本的例子:
function custom_excerpt_length( $length ) {
return 20; // 显示20个单词
}
add_filter( 'excerpt_length', 'custom_excerpt_length' );
function custom_excerpt_more( $more ) {
return '... <a href="' . get_permalink() . '" class="more-link">Read More</a>';
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );
将这些代码添加到你的主题的 functions.php
文件中,就可以自定义摘要的长度和结束文本了。