duandian8251 2018-03-26 17:25
浏览 56

php类中的WordPress主题激活挂钩

I want to run a function when my theme is activated. I have to add the theme activation hook within a php class:

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();

When I activate my theme I get the following php error:

PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'My_Class_Name' does not have a method 'activate' in /Applications/MAMP/htdocs/wp-themes/test/wp-includes/class-wp-hook.php on line 288

If I use add_action('after_switch_theme', 'activate' );

I get

PHP Fatal error: Cannot access self:: when no class scope is active

How can I make the hook work?

  • 写回答

1条回答 默认 最新

  • dongzhong6675 2018-03-26 17:56
    关注

    Here a simple way i made it work.

    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();
    

    Here is another way you can instantiate.

    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();
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!