0

I am creating a plugin in which my custom sidebar widget changes content depending on the page it is loading on. One way to do this is

// Register and load the widget
function custom_register_widget() {
    register_widget( 'custom_widget' );
}

//trigger on every sidebar load
add_action('dynamic_sidebar', 'custom_register_widget' );

However, this calls the register_widget() on every page load ( thereby making changes to WordPress DB ), thus slowing the page speed.

Is there an efficient way to this?

1
  • register_widget does not make changes to the database. Also remember that if dynamic_sidebar runs every time a sidebar is loaded, and you have more than one sidebar, you'll get duplication. And if no sidebar is displayed, the widget is never registered, and won't be available in the widget admin
    – Tom J Nowell
    Commented Nov 27, 2018 at 3:34

1 Answer 1

1

register_widget() doesn't make any changes to the database. All it does is make a particular widget available to be used. It shouldn't be used on the dynamic_sidebar hook. It's supposed to be used on the widgets_init hook.

If you want the contents of a widget to change depending on the current page, then that logic needs to be in the widget itself, in the widget() method:

class My_Widget extends WP_Widget {
    public function __construct() {}

    public function widget( $args, $instance ) {
        if ( is_page() ) {
            $page_id = get_queried_object_id();

            echo get_the_title( $page_id );
        }
    }

    public function form( $instance ) {}

    public function update( $new_instance, $old_instance ) {}
}

That example will output the current page title, if you're viewing a page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.