在WordPress中,the_excerpt()
和 the_content()
是两个常用的模板函数,用于显示文章的摘要和全文。以下是如何使用这两个函数的步骤:
使用 the_excerpt()
显示文章摘要
-
确保摘要功能已启用:
默认情况下,WordPress会自动生成文章的摘要,它通常是从文章的第一段内容中提取的,或者你可以手动设置摘要。 -
在模板文件中调用
the_excerpt()
:
在你的WordPress主题的适当位置(通常是循环内),调用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; ?>
-
自定义摘要长度:
如果你想自定义摘要的长度,可以使用excerpt_length
过滤器。function custom_excerpt_length() { return 20; // 摘要的字符数 } add_filter( 'excerpt_length', 'custom_excerpt_length' );
使用 the_content()
显示文章全文
-
在模板文件中调用
the_content()
:
在单个文章页面的模板文件(通常是single.php
)中,调用the_content()
函数来显示文章的完整内容。<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <h2><?php the_title(); ?></h2> <?php the_content(); ?> <?php endwhile; endif; ?>
-
自动分页:
如果文章很长,WordPress会自动将内容分页。如果你想禁用自动分页,可以使用the_content()
的参数。<?php the_content( 'Continue reading »' ); ?>
-
添加“阅读更多”链接:
在首页或其他存档页面,你可能会想在摘要后添加一个“阅读更多”链接,这可以通过the_content()
的参数实现。<?php the_content( '阅读更多 »' ); ?>
请注意,the_excerpt()
通常不包含HTML标签,而 the_content()
会保留所有的HTML格式和短代码。
在使用这些函数时,确保它们位于WordPress的循环内,这样它们才能正确地获取当前文章的内容。