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 1 year has passed since last update.

【Wordpress】the_title() と get_the_title() の違い、知っていますか?

Last updated at Posted at 2023-06-15

前提

ページタイトルを出すのに、the_title()get_the_title()があったり...
サムネ画像出力にもthe_post_thumbnail()get_the_post_thumbnail()があったり。

非常に似ているこちら、違いはご存じだろうか?

echoを含むか否かの違い

結論としては、echoを含んでいて、その記述をするだけで出力できるのがthe_title()the_post_thumbnail()

例えばHTML上で、<?php the_post_thumbnail(); ?>と記述するだけで出力できるので、記述量が減るので便利。

get_the_title()や、get_the_post_thumbnail()はechoを含まないので、例えばphpのコードブロック内でechoでHTMLと一緒に出力するときに便利。

実例

つまり、以下は同じ出力結果を得られる。

<?php the_post_thumbnail(); ?>
<?php echo get_the_post_thumbnail(); ?>

Wordpressの他の人の作ったテーマフォルダを見てると、こういうのをよく見る。

<?php if (condition): ?>

html code to run if condition is true

<?php else: ?>

html code to run if condition is false

<?php endif ?>

こうやって、phpのコードブロックに全ての記述を入れず、細切れにphpのコードをHTMLに埋め込む書き方をする場合はthe_title()を使った方が便利だろう。

ただ、私のようにインデントがないと}の閉じ位置がわかりにくい人にとっては、phpのコードはまとめて記述したいので、get_the_title()をよく使うことになりそうだ。

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?