Class not found in add_action at static function

644 Views Asked by At

I'm writing a plugin for WordPress for my own website and I have an error when I try to call add_action inside a public static function

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

The same is if I use

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

In someway WordPress query monitor shows the error: "SitemapGeneratorLoader" is not found.

if I use 'init' no errors are shown

Someone knows why?

1

There are 1 best solutions below

9
On

To access function within the same class use

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

Also verify your hook here https://developer.wordpress.org/reference/functions/do_robots/, I think it should be 'robots_txt' instead of 'do_robots'.