4

When i add the

<?php the_title(); ?> 

to a page template file it works and is able to pull the page title inside html tags however if i wanted to add

<?php the_title(); ?> 

to a single page itself how would i do so?

Also to provide more context; i want to add the

<?php the_title(); ?> 

inside a shortcode in order to have the shortcode replace part of it with the specific page's title, how would i do that?

For Example: the shortcode [products columns="3" attribute="season" terms="warm" orderby="date"] Except replace the seasons with the page title... thanks!

1 Answer 1

8

You can create a shortcode to fetch the title of current page. Try copying the following snippet in your child theme's functions.php

function post_title_shortcode(){
    return get_the_title();
}
add_shortcode('post_title','post_title_shortcode');

Use [post_title] shortcode to display the title of the post or page.

5
  • global $post; and $post->ID are redundant. Sep 18, 2018 at 0:57
  • 1
    I updated the answer.
    – Akshat
    Sep 18, 2018 at 1:14
  • 2
    So now that the function is just returning get_the_title(), you might as well just use add_shortcode('post_title','get_the_title'); Sep 18, 2018 at 1:15
  • This works on displaying the page title inside the page but it doesn't work at adding it inside the shortcode so for example: [product_category category="[post_title]" columns="3" per_page="5"] it results in just showing the following " columns="4" per_page="5"] Where the normal shortcode is [product_category category="men" columns="3" per_page="14"]
    – sn22
    Sep 18, 2018 at 16:16
  • 1
    You can't use shortcodes inside shortcodes like that. You should really find an alternative way to do what you want. Sep 19, 2018 at 7:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.