从 WordPress 帖子中获取有限的纯文本摘录?

2024-01-02

我在自己的主题模板中使用“The Loop”来获取 WordPress 的最后三篇文章。

<?php
$args = array( 'numberposts' => 3 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>

    <!-- DATE -->
    <div class="date">
    <?php the_time('m F Y');?>
    </div>

    <!-- TITLE -->
    <div class="title">
    <?php the_title(); ?>
    </div>

    <!-- SNIPPET -->
    <div class="content">
    <?php the_excerpt(); ?>
    </div>

<?php endforeach; ?>

一切都工作正常 - 除了the_excerpt()。我需要帖子中大约 15-20 个单词的纯文本来显示为预览,而不是完整摘录或整个帖子内容正文。我该怎么做呢?


为什么要避免使用 PHPsubstr()

substr()根据字符数而不是整个单词进行截断,最后一个单词很可能会被截断。它还可能会截断结束 HTML 标记并返回格式错误的 HTML,从而搞乱布局的其余部分。

不要重新发明轮子!

WordPress 3.3 及以上版本有新的核心功能 https://developer.wordpress.org/reference/functions/wp_trim_words/ called wp_trim_words()

参数细分:

wp_trim_words($text, $num_words, $more);


$text
    (string) (required) Text to trim
    Default: None

$num_words
    (integer) (optional) Number of words
    Default: 55

$more
    (string) (optional) What to append if $text needs to be trimmed.
    Default: '…'

用法示例:

<?php echo wp_trim_words(get_the_excerpt(), 30, '...'); ?>

<?php echo wp_trim_words(get_the_content(), 50, '... read more &gt;'); ?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 WordPress 帖子中获取有限的纯文本摘录? 的相关文章

随机推荐