You’re getting the output there because dynamic_sidebar()
displays/echoes the output (widgets in the specific sidebar), so the output is echoed right when the shortcode function is called, which is before the $data
is actually echoed.
And you can fix that using output buffering:
-
Either append the output to
$data
:$data.='</div>'; $data.='<div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"><div class="cp-social">'; if (is_active_sidebar('footer-social')) : ob_start(); dynamic_sidebar('footer-social'); // echoes the widgets $data .= ob_get_clean(); // append the output endif; $data.='</div><div class="cp-newsletter">'; if (is_active_sidebar('cp_newsletter')) : ob_start(); dynamic_sidebar('cp_newsletter'); // echoes the widgets $data .= ob_get_clean(); // append the output endif; $data.='</div></div></div></div></div>';
You can turn on/off output buffering at anytime, and you should do the same as above with the
cp_newsletter
sidebar.Update: Not sure why this option is not working for you, but maybe the updated code can help?
-
Or (maybe easier), echo everything in your function:
function Post_home() { ob_start(); ?> <div class="cp-seeWrapper"> <div class="container"> <div class="row"> <div class="col-xl-8 col-lg-8 col-md-8 col-sm-12 col-xs-12"> </div> <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="cp-social"> <?php if ( is_active_sidebar( 'social-footer' ) ) dynamic_sidebar( 'social-footer' ); ?> </div> <div class="cp-newsletter"> <?php if ( is_active_sidebar( 'cp_newsletter' ) ) dynamic_sidebar( 'cp_newsletter' ); ?> </div> </div> </div> </div> </div> <?php return ob_get_clean(); }
UPDATE
For option #1, you might want to consider caching either the widgets (i.e. the output returned by the ob_get_clean()
call) or your shortcode output (i.e. the entire content of the $data
). I suggested that for performance reasons where the shortcode could be called twice or more on the same page.
Additionally, if you’re going to use option #2 (echo everything), then you might want to consider creating a template and do something like:
function Post_home() {
ob_start();
locate_template( 'my-template.php', true );
return ob_get_clean();
}
5
solved Dynamic HTML not displaying at respective place