index.phpに投稿記事のをアーカイブ表示するようにしています。
アーカイブ表示については、
このような感じで、アーカイブ表示しています。
青文字のタイトルが15文字超えると、タイトルが2行で表示されて不恰好なので、15文字超えると「・・・」と表示するようにしたいです。
やりたいこと
- タイトルの文字数制限 制限超えると「・・・」と表示
- タイトルには記事のリンクがつくようにする
以下のコードをindex.phpに埋め込んでいます。
php
1<?php 2 if ( is_single() ) { 3 the_title( '<h1 class="entry-title">', '</h1>' ); 4 5 } else { 6 the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' ); 7 } 8 9?>
このコードで各記事のアーカイブ表示のタイトルを表示しているのですが、
このタイトルを文字数制限したいと考えています。
以下使用しようとしているコードです。
PHP
1<?php 2if (strlen($post->post_title) > 15) { 3 echo mb_substr(the_title($before = '<h1 class="entry-title">', $after = '</h1>', FALSE), 0, 15) . '...'; 4} else { 5 the_title(); 6} ?> 7
またはこのコード
PHP
1<?php 2if(mb_strlen($post->post_title, 'UTF-8')>15){ 3 $title= mb_substr($post->post_title, 0, 15, 'UTF-8'); 4 echo $title.'……'; 5}else{ 6 echo $post->post_title; 7} 8?>
タイトル前後にタグがつくように、the_title(before,after)を入れていますが、
これを使用しながら、文字数制限をかける方法がよくわかりません
以下、自分なりに組み合わせてみたのですが、上手くいきませんでした。
PHP
1<?php 2if ( is_single() ) { 3 if (strlen($post->post_title) > 15) { 4 echo mb_substr(the_title($before = '<h1 class="entry-title">', $after = '</h1>', FALSE), 0, 15) . '...'; } else { 5 the_title(); 6 } 7 8} else { 9 if (strlen($post->post_title) > 15) { 10 echo mb_substr(the_title($before = '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', $after = '</a></h2>', FALSE), 0, 15) . '...'; } else { 11 the_title(); 12 } 13 } 14?>
みにくくてすみません。
お手数ですが、よろしくお願いします。
対策①
頂いたコードをそのまま置き換えると以下のエラーが返ってきました。
PHP
1<?php 2if ( is_single() ) { 3 if ( strlen( get_the_title() ) > 15) { 4 echo '<h1 class="entry-title">'.mb_substr( get_the_title(), 0, 15).'...</h1>'; 5 } else { 6 the_title(); 7 } 8 9} else { 10 if ( strlen( get_the_title() ) > 15) { 11 echo '<h2 class="entry-title"><a href="'.esc_url( get_permalink() ).'" rel="bookmark">' 12 echo mb_substr( get_the_title(), 0, 15 ).'...'; 13 echo '</a></h2>'; 14 } else { 15 the_title(); 16 } 17} 18?>
Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in /home/・・・/template-parts/content-for-index.php on line 16
この16行目に相当するのは以下のコード部分です。
PHP
1echo mb_substr( get_the_title(), 0, 15 ).'...';
上手くインデントつけられなかったので、みにくいですが現状このような状態です。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。