Shortcode output always showing at top of custom t

2019-09-12 10:17发布

问题:

my shortcode output always appear on the top of my custom template.

custom template

$tag= 'the_content';
remove_all_filters( $tag);
$postid = get_the_ID();
$post = get_post($postid);
$content = do_shortcode($post->post_content);

ob_start();
echo $content;
$result = ob_get_contents();
ob_end_clean();
return $result;

custom shortcode

function signupform_shortcode( $atts ) {
   extract( shortcode_atts( array(
      'socialmkt' => 'aweber'
      ), $atts ) );

   if($socialmkt == 'aweber'){
      if($display == 'popup') {
        return include_once('modal-aweber.php');
      }

   }
}
add_shortcode('signupform', 'signupform_shortcode');

The shortcode it's place in the middle of a html landing. I try adding ob_start() that i read in other posts but still not working.

回答1:

Your shortcode callback is going to output content rather than return it which is why you're seeing it appear at the top of your page.

Using output buffering (ob_start() / ob_get_contents()) is a valid way of addressing the problem however you need to move the code.

Output buffering should be taking place inside your shortcode callback where the return value is required instead of output.

function signupform_shortcode( $atts ) {
    extract( shortcode_atts( array(
        'socialmkt' => 'aweber'
    ), $atts ) );

    // Begin output buffering here. Any output below will be stored in a buffer.
    ob_start();

    if ( $socialmkt == 'aweber' ) {
        if ( $display == 'popup' ) {

            // Return, as previously used, doesn't help in this context.
            include_once( 'modal-aweber.php' );
        }

    }

    // Return (and delete unlike ob_get_contents()) the content of the buffer.
    return ob_get_clean();
}
add_shortcode( 'signupform', 'signupform_shortcode' );