【问题标题】:Show excerpt on front page using the_content(); and ACF使用 the_content() 在首页显示摘录;和 ACF
【发布时间】:2017-01-15 08:40:40
【问题描述】:

我需要在我的主页上显示摘录。我有标准帖子和自定义帖子类型“网络研讨会”。 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;
}

现在我显示了两种帖子类型,但它显示了整个“描述”或“网络研讨会描述”字段。我需要将其修剪为 40 个字并添加一个“...阅读更多”,其中“阅读更多”是文章的链接。

我已经尝试过了,但它只适用于普通的“帖子”类型字段“描述”它不适用于我的“网络研讨会”自定义帖子类型 -> 自定义字段“网络研讨会描述”

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

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

【问题讨论】:

    标签: php wordpress filter custom-fields display


    【解决方案1】:

    不确定这是否会对处于类似情况的任何人有所帮助,但这就是我解决它的方法。首先,在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 } ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多