Using WordPress ‘load_default_widgets’ PHP filter

The load_default_widgets WordPress PHP Filter allows you to control the loading of the default Widgets library.

Usage

add_filter('load_default_widgets', 'your_custom_function');
function your_custom_function($wp_maybe_load_widgets) {
    // your custom code here
    return $wp_maybe_load_widgets;
}

Parameters

  • $wp_maybe_load_widgets (bool): Determines if the Widgets library should be loaded. Default is true.

More information

See WordPress Developer Resources: load_default_widgets

Examples

Disable Widgets Library

Prevent the Widgets library from loading.

add_filter('load_default_widgets', '__return_false');

Enable Widgets Library

Explicitly allow the Widgets library to load (default behavior).

add_filter('load_default_widgets', '__return_true');

Load Widgets Library Conditionally

Load the Widgets library only for logged-in users.

add_filter('load_default_widgets', 'load_widgets_for_logged_in_users');
function load_widgets_for_logged_in_users($wp_maybe_load_widgets) {
    if (is_user_logged_in()) {
        return true;
    } else {
        return false;
    }
}

Load Widgets Library on Specific Pages

Load the Widgets library only on the homepage and specific pages by their IDs.

add_filter('load_default_widgets', 'load_widgets_on_specific_pages');
function load_widgets_on_specific_pages($wp_maybe_load_widgets) {
    $allowed_pages = array(10, 20, 30); // Replace with your page IDs
    if (is_front_page() || in_array(get_the_ID(), $allowed_pages)) {
        return true;
    } else {
        return false;
    }
}

Load Widgets Library for Specific User Roles

Load the Widgets library only for users with the ‘editor’ or ‘administrator’ role.

add_filter('load_default_widgets', 'load_widgets_for_specific_roles');
function load_widgets_for_specific_roles($wp_maybe_load_widgets) {
    if (current_user_can('editor') || current_user_can('administrator')) {
        return true;
    } else {
        return false;
    }
}