Any reason this code does not work in the admin section (specifically when ajaxing but the issue persists on other pages) of WordPress but works just fine

ob_start();
    dynamic_sidebar('frontpage_widgets');
$content = ob_get_clean();

print_r($content); // nothing 

the sidebars are set from what I see (because I have called my code which registered the sidebars)

print_r($GLOBALS['wp_registered_sidebars'])

    Array
    (
        [frontpage_widgets] => Array
            (
                [name] => Frontpage Widgets
                [id] => frontpage_widgets
                dynamic_sidebar() returns false in admin section => Widgets for the Frontpage Widgetspage
                [class] => 
                [before_widget] => 
                ...

Is there something preventing the widgets from displaying in the admin section?

Edit – I seems that the widgets are not being set globally: $wp_registered_widgets is empty

2 Answers
2

Yes, you have to make sure to hook this function at some point after the sidebars are registered. It’s not quite explained, but implied in the codex that this function dynamic_sidebar( $index ) expects them to be registered and loaded as registered by the time it runs. Otherwise, it won’t have anything to match the $index argument, which in your case is 'frontpage_widgets'.

If your sidebars were registered by number, they should be retrieved
by number. If they had names when you registered them, use their names
to retrieve them.

If I had to guess off hand, I’d say wp_loaded() is the earliest action you can safely hook it to. Or if you need to, you can hook into wp_register_sidebar_widget to hook into the specific widget you are testing for.

I assume you were just using the object buffering for debugging purposes. You can almost always find an appropriate action to hook or area of your template to edit. I’m finding that understanding the order in which actions are fired is invaluable. Take a look at this answer by birgire as a good reference for when different actions are fired. This will make debugging a lot easier. Usually, finding the proper place to hook will be fairly intuitive depending on what you’re working with.

Leave a Reply

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