0

I'm trying to override a method (my_packages) from the WP Job Manager Paid Listings plugin by extending it's class from within a custom plugin

Here is how the source code (none-related code removed) is set up...

class WC_Paid_Listings_Orders {

  private static $instance;

  public static function get_instance() {

      return null === self::$instance ? ( self::$instance = new self ) : self::$instance;
  }

  public function __construct() {

    add_action( 'woocommerce_before_my_account', array( $this, 'my_packages' ) );

  }

  public function my_packages() {

    // This is what I want to unhook

  }

}

How would I 'unhook' my_packages? This is what I have thus far (and failing with)! I'm guessing it's to do with the instance? I've tries all sorts of iterations from examples on here but to no avail - Operating at the edge of my knowledge here I'm afraid.

class cvl_override_defaults extends WC_Paid_Listings_Orders {

   public function __construct() {

    remove_action('woocommerce_before_my_account', array( $this, 'my_packages'));

    add_action( 'woocommerce_before_my_account', array( $this, 'new_my_packages' ) );

   }

   public function new_my_packages() {

     // New output goes in here

   }

}

TIA!

0

Problem lies in this line:

remove_action('woocommerce_before_my_account', array( $this, 'my_packages'));

This won't remove action registered by parent class, because $this is a different object in this case, so you won't remove any action at all.

So how to remove such action? Since you can't access the same $this value in your class, you'll have to iterate through all filters and remove the given one manually.

Here's a good example how to do that:

https://wordpress.stackexchange.com/a/239431/34172

  • Thank you - I thought it may be something to do with this after some further reading. Working!!! :D – richerimage Nov 12 '18 at 21:00
  • WC_Paid_Listings_Orders has a method for getting the instance of the class, so iterating through filters manually shouldn't be necessary. – Jacob Peattie Nov 13 '18 at 10:24
2

When an action is added using a specific instance of a class (when you see $this), to remove the action you need to pass the same instance of the class to remove_action().

Since WC_Paid_Listings_Orders is a Singleton (it appears), there is only one instance of the class, and you can get that instance using the get_instance() method. You can then use that instance to remove the action.

$wc_paid_listings_orders = WC_Paid_Listings_Orders::get_instance();
remove_action( $wc_paid_listings_orders, 'my_packages' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.