This tutorial provides the steps to create and add a shortcode for post title using WordPress and Genesis way.
Use Only one shortcode as per your requirement.
For WordPress Themes
Type 1. Output Post title as Text
add_shortcode( 'custom_post_title', 'custom_post_title_shortcode' ); function custom_post_title_shortcode() { return get_the_title(); }
Type 2. Output Post title with additional HTML
add_shortcode( 'custom_post_title', 'custom_post_title_shortcode' ); function custom_post_title_shortcode() { return '<h4 class="custom-post-title">'.get_the_title().'</h4>'; }
Type 3. Output Post title with Post link and additional HTML
add_shortcode( 'custom_post_title', 'custom_post_title_shortcode' ); function custom_post_title_shortcode() { return '<h4 class="entry-title" itemprop="headline"><a href=" '.get_permalink().'">'.get_the_title().'</a></h4>'; }
or
add_shortcode( 'custom_post_title', 'custom_post_title_shortcode' ); function custom_post_title_shortcode() { return '<h4 class="entry-title" itemprop="headline"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>'; }
Usage:
[custom_post_title]
You can restrict the shortcode to work on specific post and location by following WordPress conditional Tags.
Bonus:
/* title to get the post title */ function my_custom_post_title() { global $wp_query; return get_the_title($wp_query->post->ID); } /* Add shortcode */ add_shortcode('wp_custom_post_title', 'my_custom_post_title');
Usage:
[wp_custom_post_title]
For Genesis Framework
You can output post title in Genesis Framework using genesis_do_post_title();
in any Type of mentioned in for WordPress themes.
or
Use this in functions.php
/** * Post title shortcode. * `[post_title]` to use in the loop. Or `[post_title id="123"]` to get a specific post's title, by ID * * @return string The post's title. */ add_shortcode( 'post_title', function( $atts ) { $atts = shortcode_atts( array( 'id' => get_the_ID(), ), $atts, 'post_title' ); return get_the_title( absint( $atts['id'] ) ); });