How do I insert output from a PHP return into an HTML <div>? (I’m using WordPress)

I created a quick WordPress shortcode so my writers can easily style out a subtitle in the Visual editor of a post:

function subtitle( $atts, $content = null ) {
    return '<p class="subtitle">' . $content . '</p>';
}

I want to move this output to inside a specified elsewhere in the document, example:

Read More
<div id="output_here_please"></div>

<?php the_content(); /* It is returned here wherever they place the shortcode */ ?>

What is the best way to do this? Is there a PHP or WordPress function to use, or should I create a javascript to replace innerHTML (I tried this but didn’t know how to insert it AFTER the page loads).

Thanks

Related posts

Leave a Reply

2 comments

  1. If your function is called subtitle like that, then they can insert it with:

    <div id="output_here_please">
      <?php subtitle("value", "This is some sample content"); ?>
    </div>
    
  2. The quick and dirty way of doing it is to declare a global variable – say $subtitle_content, and use it to store temporarily the html fragment you wish to display elsewhere.

    function subtitle( $atts, $content = null ) {
        $GLOBALS["subtitle_content"] = '<p class="subtitle">' . $content . '</p>';
        return "";
    }
    
    function the_content(){
        echo $GLOBALS["subtitle_content"];
        /* unset $GLOBALS["subtitle_content"]; */
    }
    

    You may want to undefine that variable once it becomes unnecessary, as written in the commented out code above.

    Documentation on $GLOBAL for your information.

    Note:

    • you may want to use more specific names for your functions, to avoid name collisions with other functions (although PHP will abruptly tell you if this happens).
    • don’t use javascript for that, this is strictly server-side cuisine.