phpforeachelementor

PHP Foreach with Elementor Widget Registration


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) {
    
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Widgets\ki__'.$filename.'() );
        }
        
    }

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


Solution

  • I think in your case use ki__widget1, not Widgets\ki__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');  
        \Elementor\Plugin::instance()->widgets_manager->register_widget_type(new $className());  
    }  }