skip to Main Content

This is what I’m trying to achieve, instead of adding all of the files one by one, I need to add all via folder/file name:

private function include_widgets_files() {
        
    private function include_widgets_files() {
        
        foreach (glob(__DIR__ . '/widgets/*.php') as $filename) {
            require_once $filename;
        }
            
    }
}

And wondering which way I should follow to register the Widgets as seen below:

public function register_widgets() {
    // Its is now safe to include Widgets files
    $this->include_widgets_files();

    // Register Widgets
    foreach (glob("widgets/*") as $filename) {
    
ElementorPlugin::instance()->widgets_manager->register_widget_type( new Widgetski__'.$filename.'() );
        }
        
    }

I don’t think it’s registering the files at require_once.

2

Answers


  1. You can try my code to include all files in the widgets directory and register the widgets.

    Include widgets files

    private function include_widgets_files() {
    
        foreach (glob(__DIR__ . '/widgets/*.php') as $filename) {
           require_once $filename;
        }
    }
    

    Note the /widgets/*.php pattern, which will match only PHP files in the widgets directory.

    Register widgets

    public function register_widgets() {  
    // Include widgets files  
    $this->include_widgets_files();
    
    // Register widgets  
    foreach (glob(__DIR__ . '/widgets/*.php') as $filename) {  
        $className = basename($filename, '.php');  
        ElementorPlugin::instance()->widgets_manager->register_widget_type(new $className());  
    }}
    
    Login or Signup to reply.
  2. I think in your case use ki__widget1, not Widgetski__widget1. Here is the corrected code according to my judgment.

      private function include_widgets_files() {  
    foreach (glob(__DIR__ . '/widgets/*.php') as $filename) {  
        require_once $filename;  
    }  
    }  
    
    public function register_widgets() {  
    // Include widgets files  
    $this->include_widgets_files();  
    
    // Get the namespace  
    $namespace = __NAMESPACE__ . '\Widgets\';  
    
    // Register widgets  
    foreach (glob(__DIR__ . '/widgets/*.php') as $filename) {  
        $className = $namespace . basename($filename, '.php');  
        ElementorPlugin::instance()->widgets_manager->register_widget_type(new $className());  
    }  }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search