使用the_content()显示首页的摘录;和ACF


Show excerpt on front page using the_content(); and ACF

我需要在我的主页上显示一个摘录。我有标准的帖子和自定义的帖子类型'网络研讨会'。CPT 'webinar'有一个自定义字段,使用ACF 'webinar_description',相当于普通帖子中的'description'。

我能够显示这两个,通过为'webinar_description'添加一个过滤器,像这样:

add_filter('the_content','add_my_custom_field');
function add_my_custom_field($data) {
    $data .= get_field('webinar_description');
    return $data;
}

现在我有两个帖子类型显示,但它显示整个'description'或'webinar_description'字段。我需要把它缩减到40个单词,并加上一个"……"阅读更多","阅读更多"是文章的链接。

我已经尝试过了,但它只适用于正常的'post'类型字段'description',它不适用于我的'webinar'自定义帖子类型->自定义字段'webinar-description'

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '<a href="' . get_permalink() . '">[Read more]</a>');?>

我如何创建一个过滤器或函数,将限制在400(或任何)字符和添加链接?

不确定这是否会帮助任何人在类似的情况下,但这就是我如何解决它。首先,在functions.php中使用自定义的post类型

function cpt_get_excerpt(){
    $excerpt = get_field('webinar_description');
    $excerpt = preg_replace(" ('[.*?'])",'',$excerpt);
    $excerpt = strip_shortcodes($excerpt);
    $excerpt = strip_tags($excerpt);
    $excerpt = substr($excerpt, 0, 400);
    $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
    $excerpt = trim(preg_replace( '/'s+/', ' ', $excerpt));
    $excerpt = $excerpt.'... <a class="c-drkGold" href="'.get_permalink($post->ID).'">Read More</a>';
    return $excerpt;
}

然后在你想要显示它的地方,根据文章类型使用if/else语句并相应地显示(这个例子来自静态首页)。

<?php 
    if( get_post_type() == 'post' ) {
        ?><p class="l-nmb"><?php
        $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '... <a href="' . get_permalink() . '" class="c-drkGold">Read more</a>'); ?> </p>
    <?php } else {
        ?><p class="l-nmb"><?php
        $content = cpt_get_excerpt(); echo mb_strimwidth($content, 0, 400, '... <a href="' . get_permalink() . '" class="c-drkGold">Read more</a>'); ?> </p>
    <?php } ?>