scott
scott

Reputation: 339

How to include page title of wordpress post in the content possibly with a shortcode

in the wordpress admin, i would like to do the following when creating a page:

Page Title: Test

Page content:

Lorem ipsum dolor [page_title] sit amet, consectetur adipiscing elit. Nunc et lectus sit amet ante vulputate ultrices at sit amet [page_title] tortor. Nam mattis commodo mi in semper. Suspendisse ut eros dolor. Morbi at odio feugiat [page_title] nunc vestibulum venenatis sit amet vitae neque. Nam ullamcorper ante ac risus malesuada id iaculis nibh ultrices.


Where it says [page_title] I would like it to print the page title (Test)

This needs to be achieved through the admin system, not hard-coded in the template.

Upvotes: 8

Views: 49677

Answers (3)

Sepster
Sepster

Reputation: 4849

Refer to the codex: Shortcode API

function myshortcode_title( ){
   return get_the_title();
}
add_shortcode( 'page_title', 'myshortcode_title' );

Add this to your theme's functions.php file.

Note that per the comments exchange between S.Visser and I in his answer - this solution will only work inside The Loop, while his will also work outside The Loop and so his is the more complete answer.

Upvotes: 21

Ashwin
Ashwin

Reputation: 1

Found this solution on web hope it will help others who face the same problem as mine. Just add the below code to functions.php file or to the page_title plugin .php file.

add_filter('get_the_excerpt', 'show_shortcode_in_excerpt');
add_filter('the_excerpt', 'show_shortcode_in_excerpt');
function show_shortcode_in_excerpt($excerpt) {
    return do_shortcode(wp_trim_words(get_the_content(), 55));
}

Upvotes: 0

S.Visser
S.Visser

Reputation: 4725

Add this to your theme, or make an plugin from it.

/* title to get the post title  */
function getPageTitle() {
  global $wp_query;
  return get_post_title($wp_query->post->ID);
}

/* Add shortcode */
add_shortcode('page_title', 'getPageTitle');

Upvotes: 5

Related Questions