把标题 截断
While working on our client’s site, the design’s width would not allow us to keep the long titles to be displayed on the homepage. After searching the web for options, we came across several plugins that would truncate WordPress titles, but they would do it sitewide whereas we only wanted it on the homepage. In this article, we will share with you how you can truncate WordPress Post Titles with PHP.
在客户网站上工作时,设计的宽度不允许我们保留长标题显示在主页上。 在网络上搜索选项后,我们遇到了多个插件,这些插件会截断WordPress标题,但它们会在整个网站上使用,而我们只希望在主页上使用它。 在本文中,我们将与您分享如何使用PHP截断WordPress帖子标题。
First open your index.php or the file location where you want to truncate the title. Then paste the following code to replace your the_title tag.
首先打开index.php或要截断标题的文件位置。 然后粘贴以下代码以替换您的the_title标记。
<a href="<?php the_permalink() ?>">
<?php
$thetitle = $post->post_title; /* or you can use get_the_title() */
$getlength = strlen($thetitle);
$thelength = 25;
echo substr($thetitle, 0, $thelength);
if ($getlength > $thelength) echo "...";
?>
</a>
Make sure you edit the $thelength variable from 25 to the character count of your need. You would have to estimate the count for your theme design. The code adds the length variable and then use the conditional tag to see if the title length matches our desired length. If it is longer, then the code adds ‘…’ in front. Most of the time, you will use this only on specific areas where the width is fixed in the theme.
确保将$ thelength变量从25编辑为所需的字符数。 您将不得不估计主题设计的数量。 该代码添加了length变量,然后使用条件标签来查看标题长度是否与我们期望的长度匹配。 如果更长,则代码在前面添加“ ...”。 大多数情况下,您只会在主题中宽度固定的特定区域使用此功能。
*This is a good code to have as a theme designer*.
*作为主题设计师,这是一个很好的代码*。
Source: Codezroz
资料来源: Codezroz
翻译自: https://www.wpbeginner.com/wp-themes/how-to-truncate-wordpress-post-titles-with-php/
把标题 截断