插件中类方法中的add_action在插件文件外部调用时不起作用


add_action located in a class method in plugins do not work when called outside the plugin file

我有一个简单而单一的类,位于插件中自己目录中的一个文件中。

该类只有一个目的,即使用remove_action删除一些不需要的wordpress操作,它只是许多remove_action()函数调用的简单包装器。

现在,问题是,当试图在类自己的文件之外实例化类时。然后所有的remove_action()函数调用都没有完成它的工作,但仍然返回TRUE,如成功。这是在尝试调试简单类时发现的。

如果我实例化这个类,并在类所在的同一个文件中调用它的唯一函数,那么一切都像一个魅力。奇怪的可能只有我一个人,但我真的想在自己的文件之外调用插件类方法,就像在主题文件中一样。

有人在开发插件时遇到过这个问题吗?

<?php
// removed the plugin stuff...
class WPStylesheetLoader
{
    public $styles = array();
    public function add($identifier, $url)
    {
        $this->styles[] = array('identifier' => $identifier, 'url' => $url);
    }
    public function enqueueAll()
    {
        foreach($this->styles as $style)
        {
            wp_enqueue_style($style['identifier'], $style['url']);
        }
    }
    public function activate() {
        echo add_action('get_header', array(&$this, 'enqueueAll'));
    }
}
$stylesheet = new WPStylesheetLoader;
$stylesheet->add('normalize', get_bloginfo('template_url') . '/css/normalize.css');
$stylesheet->add('style', get_bloginfo('stylesheet_url'));
$stylesheet->add('media-queries', get_bloginfo('template_url') . '/css/media-queries.css');
$stylesheet->activate();

一些错误和奇怪的事情:

  • echo add_action()不存在。它只是add_action()

  • 打印排队样式脚本的正确挂钩是wp_enqueue_scripts

  • 你正在做插件,但从主题加载样式

  • 主题style.css总是加载的,为什么要将get_bloginfo('stylesheet_url')排队?

  • &$this是PHP 4的代码,去掉&

在以下工作中,我添加了一个__construct,以便注册插件的URL:

class WPStylesheetLoader
{
    public $styles = array();
    public $plugin_url;
    public function __construct()
    {
        $this->plugin_url = plugins_url( '/', __FILE__ );
    }
    public function add( $identifier, $url )
    {
        $this->styles[] = array(
            'identifier' => $identifier, 
            'url'        => $this->plugin_url . $url 
        );
    }
    public function enqueueAll()
    {
        foreach( $this->styles as $style )
            wp_enqueue_style( $style['identifier'], $style['url'] );
    }
    public function activate() 
    {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueueAll' ) );
    }
}
$stylesheet = new WPStylesheetLoader;
$stylesheet->add( 'normalize', 'css/normalize.css' );
$stylesheet->add( 'media-queries', 'css/media-queries.css' );
$stylesheet->activate();