How to get the title in WordPress template page

get_the_title

This is very common requirement while we are creating template in WordPress. To get title on template pages there are 2 ways.

  1. get_the_title ()
  2. the_title()

get_the_title ( int|WP_Post $post ) – We can pass the post id in the parentheses to get the particular post title by default it is $post.

the_title( string $before = ”, string $after = ”, bool $echo = true ) – Display or retrieve the current post title with optional markup.

  • $before
    (string) (Optional) Markup to prepend to the title.
    Default value: ”
  • $after
    (string) (Optional) Markup to append to the title.
    Default value: ”
  • $echo
    (bool) (Optional) Whether to
    echo or return the title. Default true for echo.
    Default value: true

Example –

<?php echo get_the_title( $post_id ); ?>

<?php the_title() ?>

Difference between the_title() and echo get_the_title()?

The two are not 100% identical, though they are close and give same results.

  • the_title() will echo content by default but the third parameter can be used to change that default.
  • the_title() prepends the optional $before and appends the optional $after arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *

× How can I help you?