LoginSignup
7
7

More than 5 years have passed since last update.

WordPress 文字数が多い場合に省略する

Last updated at Posted at 2014-05-16

長いタイトル、本文を一定文字数で省略、最後に「...」をつける。

function.php に関数を作る

function.php
/**
 * @param string $str 入力文字
 * @param int $length 最大文字数
 * @param string $append 省略時に追加する文字列
 */
function mytrimwidth($str, $length=20, $append="...") {
    if (mb_strlen($str) > $length) {
        $str = mb_substr($str, 0, $length, 'UTF-8');

        return $str .  $append;
    }

    return $str;
}

必要なテンプレートで呼び出す

index.php
<a href="<?php the_permalink(); ?>" class="title">
    <?php echo mytrimwidth($post->post_title); ?>
</a>

若干挙動は違うが、デフォルトで似たような関数はあるのでそちらでも良い

index.php
<a href="<?php the_permalink(); ?>" class="title">
    <?php echo mb_strimwidth("Hello World", 0, 40, "..."); ?>
</a>

Google の検索結果上位に出てくるコードをそのままテーマ中にコピペしているケースが多くて、ついカッとなって書いた。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7