Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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>

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

http://www.php.net/manual/ja/function.mb-strimwidth.php

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away