can I pass arguments to my function through add_action?

后端 未结 13 2158
慢半拍i
慢半拍i 2020-11-29 01:07

can I do something like that? to pass arguments to my function? I already studied add_action doc but did not figure out how to do it. What the exact syntax to pass two argum

13条回答
  •  攒了一身酷
    2020-11-29 01:22

    Build custom WP functions with classes

    This is easy with classes, as you can set object variables with the constructor, and use them in any class method. So for an example, here's how adding meta boxes could work in classes...

    // Array to pass to class
    $data = array(
        "meta_id" => "custom_wp_meta",
        "a" => true,
        "b" => true,
        // etc...
    );
    
    // Init class
    $var = new yourWpClass ($data);
    
    // Class
    class yourWpClass {
    
        // Pass $data var to class
        function __construct($init) {
            $this->box = $init; // Get data in var
            $this->meta_id = $init["meta_id"];
            add_action( 'add_meta_boxes', array(&$this, '_reg_meta') );
        }
        public function _reg_meta() {
            add_meta_box(
                $this->meta_id,
                // etc ....
            );
        }
    }
    

    If you consider __construct($arg) the same as function functionname($arg) then you should be able to avoid global variables and pass all the information you need through to any functions in the class object.

    These pages seem to be good points of reference when building wordpress meta / plugins ->

    • http://www.deluxeblogtips.com/2010/05/howto-meta-box-wordpress.html
    • https://gist.github.com/1880770

提交回复
热议问题