Pregunta

I want to modify a class, specifically the public function that creates an XML object for sending through the Xero API. Within the public function of the class is the filter return apply_filters( 'woocommerce_xero_invoice_to_xml', $xml, $this ); but $this is a keyword specific to the creation of a class so

add_filter('woocommerce_xero_invoice_to_xml', 'modify_xero_invoice');

function modify_xero_invoice($xml, $this) {
  //construct the XML
}

doesn't understand $this which is obviously used many times in the original function.

How do I use this filter properly?

¿Fue útil?

Solución

It means that the instance of the class is being passed to the filter callback. This might be useful if the class instance contains properties and methods that you might want to re-use in your filter. Take this example of a class:

class MyClass {
    public function complicated_process( $value ) {
        // Do something complex with $value.

        return $value;
    }

    public function filterable_process( $raw_value ) {
        $value = $this->complicated_process( $raw_value );

        return apply_filters( 'my_class_filter', $value, $raw_value, $this );
    }
}

This class has a method, filterable_process() which takes a raw value, uses another method (complicated_process()) to change it somehow, and then returns the processed value. However it also has a WordPress filter that allows you to modify the returned value. We can use the filter like this to add 1 to the returned value:

add_filter(
    'my_class_filter',
    function( $value ) {
        return $value + 1;
    }
);

But what if we want to add 1 to the raw value, before the complicated process is run. That might not be possible by just filtering the $value, since it's already been processed. In this example however, the filter also passes the original raw value to the callback function, as well as the instance of MyClass ($this). This allows us to use the complicated_process() method from our filter, since we have access to the original class instance:

add_filter(
    'my_class_filter',
    function( $value, $raw_value, $my_class ) {
        $value = $raw_value + 1;
        $value = $my_class->complicated_process( $raw_value );

        return $value;
    },
    10,
    3
);

Note that since $this is a reserved variable, I have accepted the class instance in my callback function with a variable name that represents the class.

So in your example, the woocommerce_xero_invoice_to_xml filter is passing along the XML that can be filtered, as $xml, but it's also passing along an instance of the class that presumably produced the XML. Depending on the specifics off the class (which are third party, and thus off topic) that might useful when it comes to filtering the XML. You just need to give it a different variable name than $this.

Licenciado bajo: CC-BY-SA con atribución
scroll top