1

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?

C. Max
  • 45
  • 1
  • 7

1 Answers1

0

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'.

  • Hello, For the first: no changes. I try a var_dump in callDoRobots and it not print For the second: I can't use add_action( 'do_robots', array( $this, 'callDoRobots' ), 100, 0 ); when not in object context. I tried all these options before your comments without any results – C. Max Oct 19 '20 at 17:00
  • Ok. Are you still getting the same error: "SitemapGeneratorLoader" is not found. for 1st approach? – Pankaj Prajapati Oct 19 '20 at 17:05
  • No with the 1st approach no errors showed but no var_dump in callDoRobots is call – C. Max Oct 19 '20 at 17:14
  • That would mean the error is fixed and there is some problem with the hook as the function attached is not getting called. – Pankaj Prajapati Oct 19 '20 at 17:19
  • Yes sure there are some problems but I don't understand why a simple var_dump in callDoRobots isn't call – C. Max Oct 19 '20 at 17:26
  • So your callDoRobots will only get called when the hook to which you have attached it will run, as your hook is not running your function is not getting called and is not running, try using it on init hook and you will see the var_dump result. – Pankaj Prajapati Oct 19 '20 at 17:31
  • Also are you calling SitemapGeneratorLoader:: enable() at the end of the class declaration, if not it will not run – Pankaj Prajapati Oct 19 '20 at 17:38
  • Try running the new code after edit had to make '__CLASS__' to just __CLASS__, had to remove ''. – Pankaj Prajapati Oct 20 '20 at 09:18
  • I did all about your suggestions before to write here and I tried another time all these options... no updates, nothing changes... – C. Max Oct 20 '20 at 10:17