我正在使用此代码。现在我要添加" ..."在每个超过10个字符的类别标题的末尾。'
样品:椰子是b ...
怎么做?
<a href="' . get_category_link($category->term_id) . '">' . substr($category->cat_name, 0, 10) . ' </a>
答案 0 :(得分:2)
您可以先检查字符串长度,看是否该字符串大于10个字符:
<?php
$current_cat = get_query_var('cat');
$categories = get_categories('orderby=id&order=desc&number=16');
foreach($categories as $category) { ?>
<div class="latest">
<?php the_post_thumbnail(array( 160,100 ), array( 'class' => 'primary' )); ?>
<img src="domain.com/images/<?php echo $category->category_nicename; ?>.jpg" />
</div>
<div class="latest-details"><a href="<?php echo get_category_link($category->term_id); ?>"><?php echo substr($category->cat_name, 0, 10); echo (strlen($category->cat_name) > 10)? "...":""; ?></a>
<?php } ?>
以下是strlen()
:http://php.net/manual/en/function.strlen.php
答案 1 :(得分:2)
if (substr($category->cat_name,0,10) != $category->cat_name)
{
$category->cat_name = substr($category->cat_name,0,10);
$category->cat_name .= '...';
}
会这样做。在此if语句之后设置输出而不使用substr(),可以将$ category-&gt; cat_name保留为对象
答案 2 :(得分:0)
您可以使用此功能:
function stringLimit($text,$limit){
$length = strlen($text);
if($length>$limit){
$finalText= substr($text,0,$limit)."...";}
else {$finalText=$text;}
return $finalText;
}
$text = stringLimit($text,10);
希望这会对你有所帮助。