0

I'm trying to develop a "simple" script where i can create a filename with a timestamp of the last edit. For this I'm trying to code a class – but I'm having problems to pass an argument to add_action. I placed this script in functions.php to fire it on my will with do_action.

class tme_form_filehash
{

    public $args;

    public function __construct( $args ) {
        $this->args = $args
        add_action( 'init_tme_form_filehash', array($this, 'tme_form_filehash'), $args );
    }

    public function tme_form_filehash( $args )
    {
        echo $args;
    }

}

$tme_form_filehash = new tme_form_filehash( $args );

and somewhere in my theme I placed

<?php do_action('init_tme_form_filehash','hello'); ?>

but still there is no echo at my wished place...what I'm doing wrong here?

  • To clear some things: of course this is not the real script. But this should just show my basic problem with the script to pass an argument in my class for the "real" script. – Patrick Dahm May 23 '16 at 17:18
  • somewhere should be after when tme_form_filehash has been initiated. Where did you add it ? Also third parameter of add_action should be priority not a string like $args. – Sumit May 23 '16 at 19:35
0

If you want to apply the add_action and do_action in combination with class object, you have to use a static function to access your class.

Try this code with your own wording/variables:

class My_Plugin {

    protected static $_instance = null;

    // Static function used to access this class
    public static function get_instance() {
        if ( self::$_instance == null ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct() {
        add_action('MY_HOOK_NAME', array($this, 'MY_HOOK_FUNCTION'), $args);
    }

    public function MY_HOOK_FUNCTION($args) { 
        echo $args;
    }

}

Then initialize your class:

My_Plugin::get_instance();

Finally you can use the do_action:

do_action('MY_HOOK_NAME', 'hello my test')

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.