Filter Hook callback error, is it due to using $this inside a filter or something else?

Problem

The issue is that WordPress uses call_user_func() or call_user_func_array() to allow plugin/theme developers to add callables to hooks. Callables, or callback functions, can be simple functions, object methods, or static class methods. We need to format the callable as either a string or array depending on the type of callback we want.

Simple Functions

Creating a callable to a simple function is nothing more than a string to a function, e.g. 'my_callable_function'. This will attempt a call to the globally namespaced function my_callable_function(). It’s also possible to add a namespaced function – '\MyNamespace\my_callable_function' – which will call the my_callable_function() function located in the MyNamespace namespace. See the PHP documentation for more information on namespaces.

Object Methods

The pseudo-variable $this is available when a method is called from within an object context. See OOP basics. If you’re not familiar with object-oriented programming, $this basically refers to the class when you’re already “inside” the class. If you want to call a method of a class as a callback, we can use this in our callable callback. In this case, the callback needs to be an array with the first index being the object and the second index being the method. [ $this, 'MyMethod' ] is a valid callback (as long as the MyMethod method exists).

We can also use any object as a callable, not just the current one. In that case, we could use [ new MyObject(), 'MyMethod' ]. This would first create the MyObject object, and then use the MyMethod method as the callable.

Static Class Methods

Further, we can use static class methods in the callable. [ 'MyClass', 'MyMethod' ] would attempt to statically call the MyMethod method in MyClass.

Solution

What does this means in this particular case?

When I look at the code provided, we see that the original callable is array( $this, 'fix_wp_get_attachment_image_svg' ). For this to work, we need to be ‘inside’ a class already and referencing a method in the same class that we want to call. Instead, we see that fix_wp_get_attachment_image_svg() is a function in the global namespace, and thus the callable is the string of the named function.

Therefore, the solution is to fix the callable, so that it points to the correct function. In this case:

 add_filter( 'wp_get_attachment_image_src', 'fix_wp_get_attachment_image_svg', 10, 4 );