Elementor Custom Modules

Creating lots of modules in you theme for Elementor? Do you want to skip the step of loading the files and classes manually? I use this code which makes things very handy, just create the php-file with the same name as the class and it will be loaded automagic.

class My_Elementor_Widgets_Loader {
  protected static $_instance = null;

  /* change path to the local directory where you put the elementor modules */
  private $path = "/php/elementor_widgets/";
  public static function instance() {
    if ( ! isset( self::$_instance ) ) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

  protected function __construct() {
    add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_widgets' ], 99 );
  }

  public function register_widgets() {
    $this->include_widgets_files();
    /* register all classes (must be named as the php files) */
    foreach(glob(get_stylesheet_directory() . "/php/elementor_widgets/*.php") as $file) {
      $path_parts = pathinfo($file);

      /* change if using other namespace, or remove '__NAMESPACE__ .' if no namespace */
      $class_name = __NAMESPACE__ . '\\Widgets\\' . $path_parts['filename'];
      \Elementor\Plugin::instance()->widgets_manager->register_widget_type( new $class_name() );
    }
  }

  public function include_widgets_files() {
    /* load all php files */
    foreach(glob(get_stylesheet_directory() . $this->path . "*.php") as $file) {
      require_once($file);
    }
  }
}

My_Elementor_Widgets_Loader::instance();

Hope this will help you!

Comments

Cart