找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
积分等级发帖收益的说明江阴论坛帮助汇总江阴论坛管理规则(必看)江阴论坛版主招聘中江阴论坛已运行
查看: 2299|回复: 0

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

[复制链接]
发表于 2010-3-26 14:40:10 | 显示全部楼层 |阅读模式
其实解决这个问题很简单,只需要一句话就行了。在 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位,根据主题的不同可以自行设置该数值,另外多余长度部分使用“…”代替。


控制 Wordpress 文章标题长度

其实我在控制文章摘要的时候也是使用的这个函数
  1. <?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 470,"......"); ?>
复制代码
来输出470个字符长度的摘要,并过滤了 HTML 标记。

原文:http://eoc.hk/archives/87.html
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|江阴人家

GMT+8, 2024-3-29 15:15 , Processed in 0.016240 second(s), 16 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表