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?
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.
register_widget
does not make changes to the database. Also remember that ifdynamic_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