【问题标题】:Wordpress: How to obtain different excerpt lengths depending on a parameterWordpress:如何根据参数获取不同的摘录长度
【发布时间】:2010-08-28 18:23:52
【问题描述】:

wordpress中的摘录长度默认为55字。

我可以用下面的代码修改这个值:

function new_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

因此,以下调用将仅返回 20 个单词:

the_excerpt();

但我不知道如何添加参数以获得不同的长度,以便我可以调用,例如:

the_excerpt(20);

the_excerpt(34);

有什么想法吗?谢谢!

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    嗯,再次回答我,解决方案其实很简单。据我所知,将参数传递给函数 my_excerpt_length() 是不可能的(除非您想修改 wordpress 的核心代码),但可以使用全局变量。所以,你可以在你的functions.php文件中添加这样的东西:

    function my_excerpt_length() {
    global $myExcerptLength;
    
    if ($myExcerptLength) {
        return $myExcerptLength;
    } else {
        return 80; //default value
        }
    }
    add_filter('excerpt_length', 'my_excerpt_length');
    

    然后,在循环中调用摘录之前,为 $myExcerptLength 指定一个值(如果您想为其余帖子设置默认值,请不要忘记将其设置回 0):

    <?php
        $myExcerptLength=35;
        echo get_the_excerpt();
        $myExcerptLength=0;
    ?>
    

    【讨论】:

      【解决方案2】:

      就我发现使用 the_excerpt() 而言,没有办法做到这一点。

      有一个类似的 StackOverflow 问题here

      我发现唯一要做的就是编写一个新函数来代替 the_excerpt() 的位置。将以下代码的一些变体放入 functions.php 并调用 limit_content($yourLength) 而不是 the_excerpt()。

      function limit_content($content_length = 250, $allowtags = true, $allowedtags = '') {
          global $post;
          $content = $post->post_content;
          $content = apply_filters('the_content', $content);
          if (!$allowtags){
              $allowedtags .= '<style>';
              $content = strip_tags($content, $allowedtags);
          }
          $wordarray = explode(' ', $content, $content_length + 1);
          if(count($wordarray) > $content_length) {
              array_pop($wordarray);
              array_push($wordarray, '...');
              $content = implode(' ', $wordarray);
              $content .= "</p>";
          }
          echo $content;
      }
      

      (功能来源:fusedthought.com

      还有一些“高级摘录”插件提供此类功能,您可以查看。

      【讨论】:

        【解决方案3】:

        谢谢你的回答,thaddeusmt。

        我终于实现了以下解决方案,它根据类别和计数器提供不同的长度($myCounter 是循环内的计数器)

        /* Custom length for the_excerpt */ 
        function my_excerpt_length($length) {
            global $myCounter;
        
            if (is_home()) {
                return 80;
            } else if(is_archive()) {
                if ($myCounter==1) {
                    return 60;
                } else {
                    return 25;
                }
            } else {
                return 80;
            }
        }
        add_filter('excerpt_length', 'my_excerpt_length');
        

        【讨论】:

          猜你喜欢
          • 2014-07-31
          • 2017-04-05
          • 1970-01-01
          • 2011-05-04
          • 2017-02-26
          • 1970-01-01
          • 2012-07-07
          • 2018-01-23
          相关资源
          最近更新 更多