0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【WordPress】投稿文字数を制御するための構文

Posted at

WordPressでサイト制作をする際に、記事一覧を表示させる際に、本文の文字数を制御する必要があります。
(そうしないと、本文がすべて表示されてレイアウトが整わない)

文字数を制限するために、つよつよエンジニアが書いたコードをそのままコピペで使って書いていたんですが、一度整理しようと思い記事を書いております。

この記事でわかること

投稿の文字数の制御の方法

やりたいこと

投稿した本文を120文字だけ表示させる。

使用したコード

index.php
<?php
$post_content = strip_tags(get_the_content());
if(mb_strlen($post_content)>120 ) {
$post_content = mb_substr($post_content,0,120);
$post_content = str_replace(array("\r", "\n"), '', $post_content).'…';
} else {
$post_content = str_replace(array("\r", "\n"), '', $post_content);
}
echo $post_content;
?>

うおっ、全然わからない。
ちょっと話がそれますが、毎回コピペコードを使っているようじゃ成長できないなと感じます。
必ず、コピペしたコードを読み解くようにすべきですね。

では、何が行われているのかみていきましょう!

1行目

index.php
$post_content = strip_tags(get_the_content());

変数を定義しています。変数$post_contentstrip_tags(get_the_content());を格納しています。

strip_tags(get_the_content());では、HTMLタグを取り除く、strip_tag()関数を使用しています。

strip_tag()関数については、こちらの記事が参考になります。
https://thewppress.com/libraries/get-the-content/

2行目

index.php
if(mb_strlen($post_content)>120 ) {

きました、if文です。
もし〜の条件のときということで、何か条件が指定されているのでしょう。

みてみます。
(mb_strlen($post_content)>120 )
strlen()関数では、引数にしてした文字列の長さを取得してくれます。
ただ、バイト数での取得となります。
コンピューターの世界では、半角と全角でバイト数が異なるようで、半角1文字1バイト・全角1文字2バイトとなるようです。

120文字だけ表示させたいって考えたときにいちいちバイト数を考えるのはめんどくさいですよね?その際に便利なのが、mb_strlen()関数です。

バイト数ではなく、文字数を取得してくれますので、半角も全角も1文字として扱えます。

なので、もし、文字数が120文字以上の場合は⋯?という文になっています。

3~4行目

index.php
$post_content = mb_substr($post_content,0,120);
$post_content = str_replace(array("\r", "\n"), '',$post_content).'…';

3行目:$post_contentの0文字目から120文字までを取得しています。
4行目:str_replaceでは検索した文字列を変換しています。

str_replace("検索を行う文字列","置き換えを行う文字列","対象の文字列");となるようなので、

検索を行う文字列=array("\r", "\n")
置き換えを行う文字列 =なし
対象の文字列 = $post_content).'…'

となります。

ここれは、改行を削除して、120文字以上のときには、...を表示するようにプログラミングされています。

5~6行目

index.php
} else {
$post_content = str_replace(array("\r", "\n"), '', $post_content);
}

ここでは、本文が120文字以下の文章に対してのプログラミングとなります。
改行を削除して、本文を表示するようにされています。

7行目

index.php
echo $post_content;

echoで$post_contentを表示する指示がだされています。

まとめ

結構理解するのが大変でしたね。イマイチ理解できていない箇所(array("\r", "\n"))
もあったりしますが、少しずつ理解していきたいと思います。

そして、私の説明で違っている点があればTwitterのDMでも良いので教えていただけると嬉しいです!

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?