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

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用