こんにちは、
一般的には、固定ページをトップページに設定したうえで、固定ページに、最近の投稿などを追加して表示するような処理をします。(今カスタマイズしようと思っているページが、index.phpの場合)
index.phpにカスタマイズを追加した場合は、いろいろ条件分岐をしないと、他のページでも固定ページの内容が表示されてしまう可能性があるためです。
その辺りは、検討済みですか?
nobita様
お返事ありがとうございます。
現在固定フロントページ(front-page.php)を作成し、トップページを表示しています。
自己解決しました。
<?php
$page_id = ページID;
$page = get_page($page_id);
if(mb_strlen($page->post_content, 'UTF-8')>115){
$content= mb_substr(strip_tags(apply_filters('the_content', $page->post_content), '<span>'), 0,115, 'UTF-8');
echo '<section>'.$content.'…<a class="more" href="'. get_permalink($page) . '">続きを読む</a>'.'</section>';
}else{
echo '<section>'.strip_tags(apply_filters('the_content', $page->post_content), '<span>').'</section>';
}
?>
方法は、いろいろありそうですがご呈示のコードから作るとすれば 以下のようになると思います。
固定ページ本文でショートコードを使っているような場合は、remove_shortcode( )等で、ショートコードを除去する必要があります。
$page_id = ページID;
$count = 120;
$more = '...';
$page = get_page( $page_id );
$page_include = apply_filters( 'the_content', $page->post_content );
echo '<section>' . wp_html_excerpt( $page_include, $count, $more ) . '</section>';
printf('<a href="%1$s">続きを読む</a>', get_permalink( $page_id ) );
あっ、自力解決おめでとうございます。
@risa28さんの解決策に合わせると、私だとこんな感じですかね
$page_id = 46303;
$count = 120;
$more = '...';
$page = get_page( $page_id );
$page_include = apply_filters( 'the_content', $page->post_content );
$content = wp_html_excerpt( $page_include, $count, $more );
echo '<section>' . $content . '</section>';
if( false !== strstr( $content, '...' ) ) {
printf('<a href="%1$s">続きを読む</a>', get_permalink( $page_id ) );
}
nobita様
ありがとうございます。
綺麗に整いました。
提示いただいたものだと<section>の外に続きを読むのリンクが表示されますが<section>の中(…の後に)続きを読むリンクを表示させる場合、どのように記述すれば良いですか?
$page_id = 46303;
$count = 120;
$more = '...';
$page = get_page( $page_id );
$page_include = apply_filters( 'the_content', $page->post_content );
$content = wp_html_excerpt( $page_include, $count, $more );
echo '<section>' . $content ;
if( false !== strstr( $content, '...' ) ) {
printf('<a href="%1$s">続きを読む</a>', get_permalink( $page_id ) );
}
echo '</section>';
続きを読むについて、考慮しておいたほうが良さそうな点を書いておきます。多分既に知っている事と思いますが、
上記のコードの場合、htmlタグを除去して指定文字数を表示、その長さが指定数以下なら、続きを読むリンクが消えます。
一方で、個別投稿には、文字列だけが記述されているのかというと、大体は画像が含まれていたり、ビデオが配置されていたりします。 あくまでテキストの長さ基準なのでそういった場合は続きを読むリンクは表示されません。
テーブル要素が記述されている場合は、フロントページには、ほぼ意味不明な文字列が並ぶことになります。(一般的な、投稿のexcerptでも同じですが、)
nobita様
ありがとうございます。
今回表示する固定ページは画像などを含まず文字のみのページなので大丈夫だと思います。
理想通りに表示することができました!
ありがとうございます!