【问题标题】:Class not found in add_action at static function在静态函数的 add_action 中找不到类
【发布时间】:2021-02-02 08:16:37
【问题描述】:

我正在为我自己的网站编写一个 WordPress 插件,当我尝试在公共静态函数中调用 add_action 时出现错误

class SitemapGeneratorLoader
{
    public static function enable() {
        // Robots.txt request
        add_action( 'do_robots', array( 'SitemapGeneratorLoader', 'callDoRobots' ), 100, 0 );
    }

   /**
    * Invokes the doRobots method of the SitemapGenerator
    */
   public static function callDoRobots() 
   {
      $this->sg = new SitemapGenerator();
      $this->sg->doRobots();
   }
}

如果我使用也是如此

add_action('do_robots', array('SitemapGeneratorLoader', 'callDoRobots'), 100, 0);

add_filter('query_vars', array('SitemapGeneratorLoader', 'registerQueryVars'), 1, 1);

add_filter('template_redirect', array(CLASS, 'doTemplateRedirect'), 1, 0);

在某种程度上,WordPress 查询监视器显示错误:找不到“SitemapGeneratorLoader”。

如果我使用“init”,则不会显示错误

有人知道为什么吗?

【问题讨论】:

    标签: wordpress plugins php-7 add-action


    【解决方案1】:

    要访问同一类中的函数,请使用

    public static function enable() {
         // Robots.txt request
         add_action( 'robots_txt', array( __CLASS__, 'callDoRobots' ), 10, 0 );
    }
    

    还要在这里验证你的钩子https://developer.wordpress.org/reference/functions/do_robots/,我认为它应该是“robots_txt”而不是“do_robots”。

    【讨论】:

    • 您好,对于第一个:没有变化。我在 callDoRobots 中尝试了一个 var_dump,但它没有打印第二个:我不能使用 add_action( 'do_robots', array( $this, 'callDoRobots' ), 100, 0 );当不在对象上下文中时。我在您的 cmets 之前尝试了所有这些选项,但没有任何结果
    • 好的。您是否仍然收到相同的错误:未找到“SitemapGeneratorLoader”。第一种方法?
    • 没有,第一种方法没有显示错误,但 callDoRobots 中没有 var_dump 被调用
    • 这意味着错误已修复,并且挂钩存在一些问题,因为未调用附加的函数。
    • 是的,肯定有一些问题,但我不明白为什么 callDoRobots 中的简单 var_dump 不被调用
    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多