How do I create a shortcode for a WordPress sidebar?

Hi

The following code will register your shortcode and whenever you will call [add_sidebar] anywhere it will load the ‘gutenbar’ sidebar.

add_shortcode( 'add_sidebar', 'wphelp_custom_sidebar' );
function wphelp_custom_sidebar(){
    dynamic_sidebar('gutenbar');
}

custom_sidebars is just registering the sidebar but if you want to use that through shortcode then you have to call it through the function https://developer.wordpress.org/reference/functions/dynamic_sidebar/

Moderator
Jan Dembowski

(@jdembowski)

Forum Moderator and Brute Squad

@starapple Don’t create duplicate topics. I’ve archived your other topic.

Thanks moderator. I’m sure you saw my follow up: “Could an admin please delete this as I corrected the title and reposted the question.”

Thanks.

@prashantvatsh, thanks for your reply. It’s on the right track but seems to create an error in the block editor: “Updating failed. The response is not a valid JSON response.”

The sidebar shows in the preview but at the top left of the page rather than in the column where I inserted the shortcode.

Please try something like return dynamic_sidebar('gutenbar'); instead of just dynamic_sidebar('gutenbar');

Using return gives the same results. Not valid JSON and sidebar at top of post.

ob_start(); 
dynamic_sidebar( 'gutenbar'); 
$sidebar_left = ob_get_clean(); 
$html = ' <div class="sidebar-content"> ' . $sidebar_left . ' </div> '; 
return $html;

Please replace return dynamic_sidebar('gutenbar'); with the above code. Hopefully, this will work.

You’ve hit the nail on the head @prashantvatsh

It seems that in me trying to avoid using a multiplicity of plugins, we’ve almost created another. lolol

Thanks for your time an patience. A true Lion.

Will mark this as resolved.



Source link