WordPress.org

Ready to get started?Download WordPress

Forums

How to get shortcode data/content in PHP template file. (2 posts)

  1. ravikiran patil
    Member
    Posted 1 year ago #

    Hello,

    I have created a shortcode i.e. [post-title] to display title. below is my code in functions.php.

    function post_title_shortcode( $atts, $content = null, $shortcodename ="" ) {
    extract(shortcode_atts(array(
    'id' => '',
    ), $atts));

    return '<div class="'. $shortcodename .'">' . $content . '</div>';
    }
    add_shortcode('post-title', 'post_title_shortcode');

    I want to display the data/content of the [post-title] shortcode, so I used <?php echo do_shortcode('[post-title]'); ?> code in my PHP template but the problem is that it's only showing the html part i.e. <div class="post-title">..</div> not the content.

    Can somebody please help me out here?

  2. bcworkz
    Member
    Posted 1 year ago #

    do_shortcode('[post-title]'); does not provide any data for the shortcode handler to use. To display content, you need to specify what the content is, for example:

    echo do_shortcode(
      '[post-title id="sample"]Sample Title[/post-title]'
    );

    I've never seen a shortcode handler passed a third parameter like $shortcodename, not that I've seen everything. Consider passing additional data as attributes instead of extra parameters just to be safe. Once you have functional script, you can experiment further if you like.

    It's also redundant to pass a hardcoded string to do_shortcode() as I have illustrated. One could just echo the desired content directly without going through the shortcode handler. People usually pass content containing shortcodes from another source, such as post content, in order to get shortcode output without the surrounding post content.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags