Is it possible to override this function/class in a child theme?
-
14-04-2021 - |
题
Is it possible to override this widget
function from a parent theme? I saw this blog, but it dealt with a simpler case.
http://venutip.com/content/right-way-override-theme-functions
parent
class Chocolat_Widget_New_Entrys extends WP_Widget {
function __construct() {...
function widget( $args, $instance ) {...
}
add_action( 'widgets_init', create_function( '', 'return register_widget( "Chocolat_Widget_New_Entrys" );' ) );
I attempted to use remove_action('widgets_init','???');
but soon realized I could not get a handle on the function that registered it!
I thought about overriding the function and creating a subclass, but still, it is registered in the parent by the name of the parent class.
I thought about just copying the whole class, but child functions.php
is loaded before parents.php
.
解决方案
You simply need to run your code on a higher priority than what the parent theme is, the default on add_action
function is 10 so you can use:
function s157343_unregister_widgets() {
unregister_widget( 'Chocolat_Widget_New_Entrys' );
}
add_action( 'widgets_init', 's157343_unregister_widgets', 20 );
This will unregister that widget. Of course, you can still create a new class that extends that widget's class to override the methods you want and register a new widget based on that:
class my_Chocolat_Widget_New_Entrys extends Chocolat_Widget_New_Entrys() {
public function __construct() {}
public function widget( $args, $instance ) {}
}
add_action( 'widgets_init', create_function( '', 'return register_widget( "my_Chocolat_Widget_New_Entrys" );' ) );
其他提示
So here is the clear example :
In functions.php :
add_action( 'widgets_init', function() {
require 'child_chocolat_widget.php';
return register_widget( "Child_Chocolat_Widget_New_Entrys" );
} );
In child_chocolat_widget.php [Custom class file, whatever name you can keep ]
class my_Chocolat_Widget_New_Entrys extends Chocolat_Widget_New_Entrys() {
public function __construct() {}
public function widget( $args, $instance ) { //override method
}
}