在WordPress中,the_excerpt()
和 the_content()
是两个常用的模板函数,用于显示文章的摘要和全文。以下是这两个函数的基本用法:
the_excerpt()
the_excerpt()
函数用于显示文章的摘要。在WordPress中,摘要通常是文章开始部分的一小段文本,或者是文章的一个手动摘录。如果没有设置手动摘录,WordPress会自动从文章内容中提取前55个单词作为摘要。
使用方法:
<?php the_excerpt(); ?>
这将在你的主题文件中输出文章的摘要。摘要通常是简短的,不包含HTML标签,并且会自动加上一个“阅读更多”链接(如果设置了)。
the_content()
the_content()
函数用于显示文章的完整内容,包括所有的HTML格式和短代码。
使用方法:
<?php the_content(); ?>
这将在你的主题文件中输出文章的完整内容。如果你想要在内容后面添加一个“分页”链接(如果你的文章被分页了),可以使用以下代码:
<?php the_content( 'Continue reading...' ); ?>
这里的 'Continue reading...' 是可选的,它是当文章被分页时显示的链接文本。
注意事项:
the_excerpt()
和the_content()
都应该在WordPress循环(Loop)中使用,即在while ( have_posts() ) : the_post();
和endwhile;
之间。- 如果你想要自定义摘要的长度或者格式,可以使用
excerpt_length
和excerpt_more
过滤器来修改。 - 例如,以下代码可以设置摘要的最大长度为100个字符:
function custom_excerpt_length( $length ) {
return 100;
}
add_filter( 'excerpt_length', 'custom_excerpt_length' );
- 要自定义“阅读更多”链接的文本,可以使用以下代码:
function custom_excerpt_more( $more ) {
return '... <a href="' . get_permalink() . '">Read More</a>';
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );
使用这些函数时,请确保它们位于正确的位置,并且你的主题文件已经正确地设置了WordPress循环。