Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php类中的WordPress主题激活钩子_Php_Wordpress_Class - Fatal编程技术网

php类中的WordPress主题激活钩子

php类中的WordPress主题激活钩子,php,wordpress,class,Php,Wordpress,Class,我想在我的主题被激活时运行一个函数。我必须在php类中添加主题激活挂钩: final class My_Class_Name { public static function getInstance() { if (self::$instance == null) { self::$instance = new self; self::$instance->actions();

我想在我的主题被激活时运行一个函数。我必须在php类中添加主题激活挂钩:

final class My_Class_Name {

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new self;               
            self::$instance->actions();
        } else {
            throw new BadFunctionCallException(sprintf('Plugin %s already instantiated', __CLASS__));
        }
        return self::$instance;
    }


   // some code

   add_action('after_switch_theme', array( $this, 'activate' ));

   function activate() {
      // some code
   }

   // more code

}

My_Class_Name::getInstance();
当我激活主题时,会出现以下php错误:

PHP警告:call_user_func_array()要求参数1是有效的 回调,类“My_class_Name”没有方法 在中“激活” /Applications/MAMP/htdocs/wp themes/test/wp includes/class-wp-hook.php 在线288

如果我使用
add_action('after_switch_theme','activate')

我明白了

PHP致命错误:没有活动的类作用域时无法访问self::


如何使钩子工作?

这里有一个简单的方法

final class My_Class_Name {

    // some code

    public function __construct(){
        add_action('after_switch_theme', array( $this, 'activate' ));
    }

    public function activate() {
        file_put_contents(__DIR__.'\de.log','TEST');
    }

    // more code

}

new My_Class_Name();
这里是另一种可以实例化的方法

class My_Class_Name{

    protected static $instance = null;

    public function __construct(){}

    public static function get_instance() {
        // If the single instance hasn't been set, set it now.
        if ( null == self::$instance ) {
            self::$instance = new self;
        }

        return self::$instance;
    }
}

My_Class_Name::get_instance();

实例化该类会产生致命错误。我想是因为我在使用自我实例。我已经更新了我的代码。@CyberJunkie用另一种方法更新了,你可以实例化你的类:)