Ben Spi
Ben Spi

Reputation: 806

WordPress remove_action that was added in constructor of a class

I would like to modify a plugin called WooCommerce Smart Coupons. The plugin creates a small form on the checkout page that I would like to have at a different position.

I found this class to modify the form which has the action that I would like to remove (and replace with another action):

class WC_SC_Purchase_Credit {

    /**
     * Variable to hold instance of WC_SC_Purchase_Credit
     * @var $instance
     */
    private static $instance = null;

    public function __construct() {

        # some stuff 

        add_action( 'woocommerce_checkout_after_customer_details', array( $this, 'gift_certificate_receiver_detail_form' ) );

        # some stuff 

When I do this, it tells me the variable $this is undefined

remove_action( 'woocommerce_checkout_after_customer_details', array( $this, 'gift_certificate_receiver_detail_form' ) );

When I do this, it tells me the class is not found

$test123 = new WC_SC_Purchase_Credit();
remove_action( 'woocommerce_checkout_after_customer_details', array( $test123, 'gift_certificate_receiver_detail_form' ) );

Any ideas how to remove and replace this action?

Upvotes: 0

Views: 743

Answers (2)

Ben Spi
Ben Spi

Reputation: 806

The solution to it is to get an instance of the object: WC_SC_Purchase_Credit::get_instance()

add_action('wp_loaded', 'some_function');

function some_function(){ 

  $Purchase_Credit_Form_Object = WC_SC_Purchase_Credit::get_instance();

  remove_action( 'woocommerce_checkout_after_customer_details', array( $Purchase_Credit_Form_Object, 'gift_certificate_receiver_detail_form' ) );

  add_action( 'woocommerce_checkout_before_customer_details', array( $Purchase_Credit_Form_Object, 'gift_certificate_receiver_detail_form' ) );

}

Upvotes: 1

I'm Joe Too
I'm Joe Too

Reputation: 5840

$this refers to the class if called inside a class construct. You're not calling it inside the construct which is why $this doesn't work. You need to replace $this with the class name that holds the function you're trying to unhook:

<?php
remove_action( 'woocommerce_checkout_after_customer_details', array( 'WC_SC_Purchase_Credit', 'gift_certificate_receiver_detail_form' ) );

Upvotes: 1

Related Questions