Modify existing plugin function using filter (without modifying the plugin directly)

I have the following function inside an existing plugin:

public static function init() {

    add_filter( 'wcs_view_subscription_actions', __CLASS__ . '::add_edit_address_subscription_action', 10, 2 );
}

public static function add_edit_address_subscription_action( $actions, $subscription ) {

        if ( $subscription->needs_shipping_address() && $subscription->has_status( array( 'active', 'on-hold' ) ) ) {
            $actions['change_address'] = array(
                'url'  => add_query_arg( array( 'subscription' => $subscription->get_id() ), wc_get_endpoint_url( 'edit-address', 'shipping' ) ),
                'name' => __( 'Change Address', 'woocommerce-subscriptions' ),
            );
        }

    return $actions;
}

I am trying to modify this, so that I can add something to the $actions array. Is this possible without modifying the plugin directly, can I do it by filtering in the functions.php file?

2 s
2

You can simply use the same filter with a lower or higher priority parameter to make the appropriate changes to the $actions array. That way you may create a small custom plugin (or modify the theme’s functions.php file), without having to modify the existing plugin directly.

For example: if you want your custom code to execute after add_edit_address_subscription_action function, then use a bigger priority argument (lower priority) to the wcs_view_subscription_actions filter.

Sample CODE (use this as part of a custom plugin or in your theme’s functions.php file):

// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation
add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );

function wpse_custom_action_after( $actions, $subscription ) {
    // your custom changes to $actions array HERE
    // this will be executed after add_edit_address_subscription_action function 
    return $actions;
}

On the other hand, if you want your custom code to execute before add_edit_address_subscription_action function, then use a smaller priority argument (higher priority).

Sample CODE (use this as part of a custom plugin or in your theme’s functions.php file):

// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation
add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 );    
function wpse_custom_action_before( $actions, $subscription ) {
    // your custom changes to $actions array HERE
    // this will be executed before add_edit_address_subscription_action function 
    return $actions;
}

Leave a Comment