如果条件限制在wordpress标题的单词


if condition to limit the words in wordpress title

我已经编写了这段代码来循环通过我的博客上的最新6篇文章,并在一个特殊的框中显示它们,但是有一个小问题,当我写更长的标题时,标题移动到下一行。我不能增加我的标题div的宽度,所以我需要写一个if条件来显示一个"…"如果标题移动到下一行让我们说20个字符。

<div id="freshlyWrapper">
<div id="freshlyposts">
<?php
$freshlyIonised = new WP_Query();
$freshlyIonised->query('category_name=FreshlyIonised&showposts=6');
while($freshlyIonised->have_posts()):
$freshlyIonised->the_post();
?>
<div class="freshlyionisedbox"><h3><a style='text-decoration: underline; color: #000;' href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

有一个更好的方法,用CSS:

DIV.freshlyionisedbox {
    border: 1px solid #000000;
    white-space: nowrap;
    width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
}

这样做的好处是保留了页面的语义内容,并且您不必猜测在一定数量的像素中用户屏幕上可以容纳多少个字符。

子通道:

$title = "The quick brown fox jumped over the lazy dog.";
echo strlen($title) > 25 ? substr($title, 0, 25).'...' : $title;
// The quick brown fox jumpe...

这是我通常使用的,以防止文字被剪切:

function truncate($str, $width, $cutword = false) {
    if (strlen($str) <= $width) return $str;
    list($out) = explode("'n", wordwrap($str, $width, "'n", $cutword), 2);
    return $out.'...';
}
$title = "The quick brown fox jumped over the lazy dog.";
echo truncate($title, 25); 
// The quick brown fox...
$title = "The quick brown fox";
echo truncate($title, 25); 
// The quick brown fox

Try substr:

$title = get_the_title();
if (strlen($title) > 20)
    $title = substr( $title, 0 , 20 ) . "..."; // Limits title to 20 characters.

实现如下:

<div id="freshlyWrapper">
<div id="freshlyposts">
<?php
    $freshlyIonised = new WP_Query();
    $freshlyIonised->query('category_name=FreshlyIonised&showposts=6');
    while($freshlyIonised->have_posts()):
        $freshlyIonised->the_post();
        $title = get_the_title();
        if (strlen($title) > 20)
            $title = substr( $title, 0 , 20 ) . "..."; // Limits title to 20 characters.
?>
<div class="freshlyionisedbox">
    <h3><a style='text-decoration: underline; color: #000;' href="<?php the_permalink(); ?>"><?php echo $title; ?></a></h3>

Try…

$title = get_the_title();
if (strlen($title) > 20) $title = substr($title, 0, 17) . "...";

你不需要condition, apply this

echo mb_strimwidth(get_the_title(), 0, 20, '...');