PlusOne Blog

【CSS-tips⑤】長い文章を省略して「…」を付けたい

長い文章を省略して表示する方法を紹介します。
 

1行の場合

  text-overflow: ellipsis;

・white-space を nowrap に設定する必要があります。
・overflow を hidden に設定する必要があります。
 

 

複数行の場合

  display: -webkit-box;
  -webkit-line-clamp: 3;  //表示する行数を指定
  -webkit-box-orient: vertical;

 

<対応ブラウザ(line-clamp)>
・IE以外のブラウザはほぼ対応しています。
Can I use
 

 

WordPress の場合

■the_excerpt を使用する
 投稿ページの本文を抽出して、長い文章を省略するときに利用します。

  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <?php the_excerpt(); ?>
  <?php echo get_the_excerpt(); ?>
  <?php endwhile;endif; ?>

 
 省略する文字数を変更したい場合は、次のコードを functions.php に記載します。

  function twpp_change_excerpt_length( $length ) {
    return 50;  //抜粋する文字数
  }
  add_filter( 'excerpt_length', 'twpp_change_excerpt_length', 999 );

 
 省略記号[…]を変更したい場合は、次のコードを functions.php に記載します。

  function twpp_change_excerpt_more( $more ) {
    return '......';  //省略記号にしたい文字
  }
  add_filter( 'excerpt_more', 'twpp_change_excerpt_more' );

 
 「続きを読む」とリンク付きの文字を入れる

  function twpp_change_excerpt_more( $more ) {
    $html = '<a href="' . esc_url( get_permalink() ) . '">[...続きを読む]</a>';
    return $html;
  }
  add_filter( 'excerpt_more', 'twpp_change_excerpt_more' );

 
■wp_trim_words を使用する
 タイトルなど、本文以外でも省略したい場合に使用できます。

  <?php echo wp_trim_words( get_the_title(), 30 , '…' ); ?>

第1引数は必須項目。切り取りたい文字列を指定します。
第2引数は抽出する文字数。デフォルト値は55文字に設定されています。
第3引数では切り取った文字列の後に追加したい文字を指定できます。デフォルトでは「null」です。
 

 

 

この記事を読む
記事一覧に戻る