Support » Developing with WordPress » Display Post Title from Shortcode in frontend

  • HI,
    I want to display the custom post title from shortcode in the frontend, How can I do it? I don’t want to change the actual post title.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Ramona

    (@nextend_ramona)

    Hi,

    You should create a custom field, where you can add the custom title so it wouldn’t affect the actual title.

    Advanced Custom Fields is probably the most popular choice for creating a custom field: https://wordpress.org/plugins/advanced-custom-fields/
    and they also have option to access the custom field using shortcode:
    https://www.advancedcustomfields.com/resources/shortcode/

    rgerson09

    (@rgerson09)

    To display the post title from a shortcode in the frontend of a WordPress site , you can use the following code:

    Define the shortcode function in your theme’s functions.php file:
    php

    function post_title_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'id' => get_the_ID(),
        ), $atts, 'post_title' );
    
        $post_title = get_the_title( $atts['id'] );
        return $post_title;
    }
    add_shortcode( 'post_title', 'post_title_shortcode' );
    
    1. Add the shortcode [post_title] to the content of any page or post where you want to display the post title.

    For example, if you want to display the title of the current post, you can use the shortcode like this:

    The title of this post is: [post_title]
    

    If you display the title of the specific post. you can use the short code like this.

    The title of post with ID 123 is: [post_title id="123"]
    

    When the page or post is viewed on the frontend, the shortcode will be replaced with the post title.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Display Post Title from Shortcode in frontend’ is closed to new replies.