WordPress企业主题定制/开发/优化

如何控制 WordPress 文章标题的长度

首页 » WORDPRESS主题技术 » 如何控制 WordPress 文章标题的长度

在 WordPress 里,我们使用

  1. <?php the_title(); ?>

来输出文章标题,与其相关的还有一个函数:

  1. <?php get_the_title(); ?>

简单的说说两者的关系,get_the_title() 返回值是一个字符串(文章标题),而 the_title() 就是该字符串通过 echo 输出后的值。
实际上就是 WordPress 自己在输出文章标题时进行了简化,直接用

  1. <?php the_title(); ?>

代替了

  1. <?php echo get_the_title(); ?>

除此之外这里还需要用到另外一个函数:mb_strimwidth(string str, int start, int width, [string trimmarker], [string encoding]);

mb_strimwidth() truncates string str to specified width. It returns truncated string.

If trimmarker is set, trimmarker is appended to return value.

start is start position offset. Number of characters from the beginning of string. (First character is 0)

trimmarker is string that is added to the end of string when string is truncated.

encoding is character encoding. If it is omitted, internal encoding is used.

现在大部分的 PHP 服务器都支持了 MB 库(mbstring 库 全称是 Multi-Byte String 即各种语言都有自己的编码,他们的字节数是不一样的,目前php内部的编码只支持ISO-8859-*, EUC-JP, UTF-8 其他的编码的语言是没办法在 php 程序上正确显示的。解决的方法就是通过 php 的 mbstring 函数库来解决),所以我们可以放心的使用这个用于控制字符串长度的函数:

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

那么我们只需要用上面这个函数替换 WordPress 原有的

  1. <?php the_title(); ?>

即可,这里我输出了字符串的第0位到第38位,根据主题的不同可以自行设置该数值,另外多余长度部分使用“…” 代替。

其实我在控制文章摘要的时候也是使用的这个函数,比如我在 D&Z Theme Pro CP 主题的首页里使用的就是

  1. <?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 470,"......"); ?>

来输出470个字符长度的摘要,并过滤了 HTML 标记。

虽然这是个很简单的方法,但我相信它对主题制作者而言还是相当实用的。

转自:http://zeuscn.net/archives/2009/12/01/wordpress-title-width-defined.html

相关项目

  • WordPress外贸企业主题

  • 最近更新

  • 热门标签