WP插件:在类中使用add_filter

Nat*_*han 3 wordpress wordpress-plugin

我正在使用WP v3.3.1,我正在尝试制作一个插件.我已经半工作了.它启动了,add_action工作,但由于某些原因我的过滤器没有被触发.当我用Google搜索时,我看到我本应该这样做,但它不起作用.我也尝试将它包括在课外,这也没有用.错误日志是从构造函数写入的,但不是xmlAddMethod.我在单个文件中测试了xmlrpc调用,但是它有效,但是在编写类时遇到了问题.

//DOESN'T WORK HERE
add_filter( 'xmlrpc_methods', array( &$this, 'xmlAddMethod') );

class TargetDomain extends Domain 
{
    public function __construct() 
    {        
        error_log('TARGET: __construct');
        //DOESN'T WORK HERE EITHER
        add_filter( 'xmlrpc_methods', array( &$this, 'xmlAddMethod') );
        parent::__construct();
    }

    function xmlAddMethod( $methods ) 
    {
        error_log('TARGET: xml_add_method');
        $methods['myBlog.publishPost'] = 'publishMyPost';
        return $methods;
    }
Run Code Online (Sandbox Code Playgroud)

mai*_*o84 7

改变这个:

add_filter( 'xmlrpc_methods', array( &$this, 'xmlAddMethod') );
Run Code Online (Sandbox Code Playgroud)

至:

add_filter( 'xmlrpc_methods', array( 'TargetDomain', 'xmlAddMethod') );
Run Code Online (Sandbox Code Playgroud)

  • @Revious 这一点也不奇怪。函数与类方法不同。[add_action](https://developer.wordpress.org/reference/functions/add_action/) 和 [add_filter](https://developer.wordpress.org/reference/functions/add_filter/) 的第二个参数接受一个变量类型为[callable](https://www.php.net/manual/en/language.types.callable.php)。PHP 中的可调用类型可以是字符串(函数)、数组(类方法)或可以提供的匿名函数(回调)。 (2认同)
  • @Revious 大部分情况是正确的。这是一般的经验法则。在这种情况下,可以传递类似于静态类方法调用的字符串(即:`'SomeClass::staticMethod'`),这种情况自 PHP 5.3 以来就已存在,但这是我所遵循的规则的唯一例外。能想到。在这些情况下,“SomeClass::staticMethod”将与“['SomeClass', 'staticMethod']”相同。 (2认同)

小智 5

您还可以使用 php 的魔法__CLASS__常量。

add_filter( 'xmlrpc_methods', array( __CLASS__, 'xmlAddMethod') );
Run Code Online (Sandbox Code Playgroud)