plugin development - How to create a wordpress widget that dynamically changes according to the page

admin2025-06-06  1

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?

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?

Share Improve this question asked Nov 27, 2018 at 3:19 mallik1055mallik1055 32 bronze badges 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
Add a comment  | 

1 Answer 1

Reset to default 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749150291a316793.html

最新回复(0)