【问题标题】:How do I show '...' when the WordPress title exceeds length当 WordPress 标题超过长度时,如何显示“...”
【发布时间】:2023-04-08 06:44:01
【问题描述】:

我有一个功能可以将标题修剪到一定长度。它确实正确地修剪了标题,但即使标题没有超过长度,它也总是显示“...”。

有谁知道怎么做,所以“...”只会在标题太长时显示?

// Title Excerpt//
function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();

    if ( $length && is_numeric($length) ) {
        $title = substr( $title, 0, $length );
    }

    if ( strlen($title)> 0 ) {
        $title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
        if ( $echo )
            echo $title;
        else
            return $title;
    }
}
//End Title Excerpt

PHP 在循环中

<?php the_titlesmall('', '', true, '15') ?>

【问题讨论】:

标签: php wordpress


【解决方案1】:

编辑:专注于修剪标题。

尝试将此功能添加到您的functions.php。

function short_title($after = '', $length) {
    $mytitle = get_the_title();
    if ( strlen($mytitle) > $length ) {
    $mytitle = substr($mytitle,0,$length);
    echo $mytitle . $after;
    } else {
    echo $mytitle;
    }
}

然后,在您希望标题出现的任何位置输入以下内容:&lt;?php short_title('...', 40); ?&gt; 这会将其限制为 40 个字符,如果超过它,则添加一个 ...。

【讨论】:

  • 你的意思是它不起作用?您将&lt;?php wp_trim_excerpt( $text ) ?&gt; 放在您希望摘录出现的位置,对吗?
  • @user3648353 查看我的最新编辑。它应该对你有更多帮助。我误解了您要求缩短标题,而不是摘录。
  • @user3648353 太好了!很高兴我能帮上忙。
【解决方案2】:

如果您不能在显示时使用 CSS 的 text-overflow: ellipsis 修剪它,我可能只使用 mb_strimwidth。这就是它的设计目的。对于基本用途,可能是这样的:

<?php echo mb_strimwidth(get_the_title(), 0, 20, '...'); ?>

...并根据需要将其放入您自己的函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多