首页 文章

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

提问于
浏览
0

我需要在我的主页上显示一段摘录 . 我有标准帖子和自定义帖子类型'网络研讨会' . CPT'网络研讨会'有一个自定义字段,使用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;
}

现在我显示了两种帖子类型,但它显示了整个“描述”或“webinar_description”字段 . 我需要修剪40个单词并添加一个'... Read More',并将'Read More'作为文章的链接 .

我试过这个,但它只适用于普通的'post'类型字段'描述'它不适用于我的'网络研讨会'自定义帖子类型 - >自定义字段'webinar-description'

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

如何创建一个限制为400(或其他)字符的过滤器或函数并添加链接?

1 回答

  • 0

    不确定这是否会帮助处于类似情况的人,但这就是我解决它的方法 . 首先,在functions.php中,使自定义帖子类型可用

    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 } ?>
    

相关问题