Recent Posts widget modification

SO I am trying to modify the Recent Posts widget but trying to wrap my head around namespacing it.
Can someone shed some light or point me in the right direction?

Here is the example:

Class My_Recent_Posts_Widget extends WP_Widget_Recent_Posts {}

And than using:

function my_recent_widget_registration() {
add_action(‘widgets_init’, ‘my_recent_widget_registration’);

But it returns App\WP_Widget_Recent_Posts not found. I understand I have to namespace it but not sure best approach here.


It looks like this code is in a file with namespace App; at the top of it. That means that you need to add the namespace to the add_action() call, and you need to adjust your class creation and calls.

Because you’re already in the App namespace, you need to “get out” of it when you extend WP_Widget_Recent_Posts; otherwise PHP will try to extend App\WP_Widget_Recent_Posts, which will probably fail. That would look like this:

Class My_Recent_Posts_Widget extends \WP_Widget_Recent_Posts {}

Then, if you want to call your class outside of the App namespace, you’ll need to do so like this: App\My_Recent_Posts_Widget. Because your my_recent_widget_registration() function is only referencing the string (name) of your class, you will need to include the full thing, so your function should look like this:

function my_recent_widget_registration() {

Callback functions like add_action() or add_filter() fire their second argument through a mechanism similar to call_user_func() (or possibly with that function exactly; I’ve never checked). What that means is that the function add_action() will call when it runs that callback will not be called with any “awareness” of the context in which that function is defined. In other words, add_action() doesn’t know that my_recent_widget_registration is in a namespace: It will just try and call my_recent_widget_registration().

That means that when you specify a callback, you need to make sure the namespace is included. The easiest way to do that is:

add_action('widgets_init', __NAMESPACE__ . '\\my_recent_widget_registration');

I can’t thank you enough for such a detailed description - I will review and test accordingly.