WordPress Shortcode Always Display on Top of Content

I am working on a page where I will have to place some buttons with specific functions. My client is making use of the basic WordPress WYSIWYG editor and I do not want to place some a lot of HTML codes on the page so I opted to make use of shortcodes instead.

I have this shortcode definition in a class’ constructor:

add_shortcode( 'analytics_optout'  , array( $this, 'analytics_optout' ) );

Then I have this analytics_optout method:

  
public function analytics_optout() {

    $output = '<div class="analytics-optout">'
               . '<a id="analytics-activate">Activate</a>'
             .'</div>';


    echo $output;

}

This works well when I place the [analytics_optout] shortcode on the page content BUT, the shortcode output displays on top of the text content.

I did some digging and found out that since I am echo-ing the output in the method, the shortcode output gets printed immediately rather than returned. Since the shortcode output gets printed, it appears before the page content.

Because of this, the shortcode output has to be returned for it be included in the content. So the method should be:

    
public function analytics_optout() {

    $output = '<div class="analytics-optout">'
               . '<a id="analytics-activate">Activate</a>'
             .'</div>';


    return $output;

}

Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *