Using add_filter inside another class

The reason you see the default value is that you are adding the filter after the filter has been applied, which results in the default value being used. The filter is applied when the object is constructed, which I’m assuming is before admin_init. If it’s after admin_init it won’t work either, but that’s because the admin_init action has already fired.

Here’s a way you could do that (I don’t like adding actions/filters in constructors, so the classes are structured a little different.

class compiler 
{
   public function generateCss(){
      $css = apply_filters( 'dynamic_css', '.your_code{}' );
      $this->content = $css;
   }
}    
$compiler = new compiler();
add_action( 'admin_init', [ $compiler, 'generateCss' ], 11 );

class my_class
{
   public function set_css(){
      add_filter( 'dynamic_css', [ $this, 'load_custom_css' );
   }
   public function load_custom_css(){
      return get_option( 'custom_css' );
   }
}
$my_class = new my_class();
add_action( 'admin_init', [ $my_class, 'set_css' ], 10 );

Leave a Comment