【问题标题】:Limit post excerpt and post content in Wordpress在 Wordpress 中限制帖子摘录和帖子内容
【发布时间】:2015-09-01 19:28:04
【问题描述】:

我有以下狙击手:

<div class="content">
                            <h2><?php echo $article->post_title ?></h2>
                            <h3><?php echo get_field( 'subtitle', $article->ID ); ?></h3>
                            <p><?php echo display_post_excerpt( $article->post_excerpt, $article->post_content ); ?></p>

                        </div>

这里是 display_post_excerpt 函数:

function display_post_excerpt( $excerpt, $content ){
    if( $excerpt != '' ){
        $text = $excerpt;
    }else{
        $text = $content;
    }

    $text = strip_tags( $text );

    return $text;

}

我想限制帖子摘录(如果帖子没有摘录,还有内容)。我不知道我应该如何继续以及在哪里(在function.php中?模板?我想我应该使用类似的东西:

if (strlen($text) > 20) {
strlen($text) == 20;
}

但由于我是一个大菜鸟,我不确定。 你能帮帮人吗?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:
    function display_post_excerpt( $excerpt, $content ){
        if( $excerpt != '' ){
            $text = $excerpt;
            if (strlen($text) > 20) {
              $text = substr($text,0,strpos($text,' ',20)) . ' ... <a href="' . get_permalink() . '">[ read more ]</a>'; } ;
             }
             else{
                $text = $content;
             }
        }
    
        return $text;
    
    }
    

    【讨论】:

    • 谢谢,这似乎有效。如果我想为 $content 添加相同的限制,那会起作用吗: function display_post_excerpt( $excerpt, $content ){ if( $excerpt != '' ){ $text = $excerpt; if (strlen($text) > 100) { $text = substr($text,0,strpos($text,' ',100)) 。 ' [...] '; } 其他 { $text = $content; if (strlen($text) > 100) { $text = substr($text,0,strpos($text,' ',100)) 。 '……'; } } } 返回$文本; }
    【解决方案2】:

    我认为更好的解决方案是将以下代码添加到您的functions.php 文件中:

    function wpt_excerpt_length($length) {
        return 16;
      }
      add_filter('excerpt_length', 'wpt_excerpt_length', 999);
    

    你可以在这里阅读更多关于摘录的信息Function Reference/the excerpt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多