LoginSignup
4

More than 5 years have passed since last update.

WordPress、長すぎるタイトルを省略する

Posted at

WordPressでタイトルを出力する「the_title()」というテンプレートタグは、常にタイトル全体を表示します。

しかし、例えばサイドエリアなどの限られた領域内にタイトルを表示したい場合に、文字数が多いときに省略できると便利です。
そこで、新しいテンプレートタグとして「the_short_title」を追加してみましょう。

テーマフォルダ内の functions.phpを編集して、次のように書き込みます。

functions.php
function the_short_title($length = 20) {
    $ret = get_the_title( $post->ID );
    if ( mb_strlen($ret) > $length ) {
        $ret = mb_substr( $ret, 0, $length ) . '...';
    }

    echo $ret;
}

そして、テーマ内で次のように記述します。

<?php the_short_title(40); ?>

パラメータを指定すればその文字数で、なにも指定しないと20文字で省略されます。

[PR] WordPress+PHP プログラム開発サポート | anygraphica

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
4