Как создать виджет категории elementor на WordPress - PullRequest
1 голос
/ 24 марта 2019

Я хочу добавить новую категорию в редактор элементов WordPress.Я нашел ссылку https://developers.elementor.com/creating-a-new-widget/,, но я не знаю, что делать.Потому что я новичок.Как добавить эти коды, в какой файл.Я имею в виду шаг за шагом.Как сделать php-файл по любому пути и как включить этот php-файл?Я могу создать новый файл php для него?или вставить их в текущий php файл elementor?

Ответы [ 4 ]

2 голосов
/ 24 марта 2019

Как и в документации: Начало работы по расширению Elementor

Сначала создайте собственный плагин, надеюсь, вы знаете, как создать собственный плагин: Создание плагинов в WordPress

Короткая демонстрация: Запомните полное Элементарное ядро ​​ записано в ООП . Принимая имя плагина как ElementorTest

<?php
/**
 * Plugin Name: ElementorTest
 * Plugin URI:  https://example.com/plugins/ElementorTest/
 * Description: Basic Elementor Extension
 * Version:     1.1
 * Author:      Ahmed Maruf
 * Author URI:  https://author.example.com/
 * License:     GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: elementortestplugin
 * Domain Path: /languages
 */

Теперь нам нужно убедиться, что нет прямого доступа к нашим файлам php плагина, и позвольте нам создать базовый скелет для создания расширение / виджет через Elementor .Ref: Инициализация плагина

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}



final class Elementor_Test_Extension {

        const VERSION = "1.1"; //Your plugin version
        const MINIMUM_ELEMENTOR_VERSION = "2.0.0"; //Minimum Elementor Version Required
        const MINIMUM_PHP_VERSION = "7.0"; //Minimum PHP version required to run your plugin

        private static $_instance = null;
        /*The plugin class should use a singleton design pattern to make sure it loads only once*/
        public static function instance() {
            if ( is_null( self::$_instance ) ) {
             self::$_instance = new self();
         }return self::$_instance;

     }
     /*

      The constructor should initiate the plugin. The init process should check for basic requirements and then then run the plugin logic. Note that If one of the basic plugin requirements fails the plugin logic won’t run.
      */
      public function __construct() {
        add_action( 'plugins_loaded', [ $this, 'init' ] );
    }
    /*Initialize all the basic requirements to run the plugin logic*/
    public function init() {
        load_plugin_textdomain( 'elementortestplugin' );

        // Check if Elementor installed and activated
        if ( ! did_action( 'elementor/loaded' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_missing_main_plugin' ] );
            return;
        }

        // Check for required Elementor version
        if ( ! version_compare( ELEMENTOR_VERSION, self::MINIMUM_ELEMENTOR_VERSION, '>=' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_minimum_elementor_version' ] );
            return;
        }

        // Check for required PHP version
        if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
            return;
        }

        // Add Plugin actions when rest requirements are passed
        add_action( 'elementor/widgets/widgets_registered', [ $this, 'init_widgets' ] );     

    }
    /*Callback function for the action hook admin notices*/
    public function admin_notice_missing_main_plugin() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $message = sprintf(
            /* translators: 1: Plugin name 2: Elementor */
            esc_html__( '"%1$s" requires "%2$s" to be installed and activated.', 'elementortestplugin' ),
            '<strong>' . esc_html__( 'Elementor Test Extension', 'elementortestplugin' ) . '</strong>',
            '<strong>' . esc_html__( 'Elementor', 'elementortestplugin' ) . '</strong>'
        );

        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );

    }

    /*Callback function for action hook admin notices upon elementor version not matching*/
    public function admin_notice_minimum_elementor_version() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $message = sprintf(
            /* translators: 1: Plugin name 2: Elementor 3: Required Elementor version */
            esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementortestplugin' ),
            '<strong>' . esc_html__( 'Elementor Test Extension', 'elementortestplugin' ) . '</strong>',
            '<strong>' . esc_html__( 'Elementor', 'elementortestplugin' ) . '</strong>',
            self::MINIMUM_ELEMENTOR_VERSION
        );

        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );

    }
    /*Callback function for action hood admin notices upon php version not matched*/
    public function admin_notice_minimum_php_version() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $message = sprintf(
            /* translators: 1: Plugin name 2: PHP 3: Required PHP version */
            esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementortestplugin' ),
            '<strong>' . esc_html__( 'Elementor Test Extension', 'elementortestplugin' ) . '</strong>',
            '<strong>' . esc_html__( 'PHP', 'elementortestplugin' ) . '</strong>',
            self::MINIMUM_PHP_VERSION
        );

        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );

    }

    /*
    @Callback function for the action hook elementor/widgets/widgets_registered
    @Create the folder widgets and the file under you custom plugin /widgets/test-widget.php
    */
    public function init_widgets() {

        // Include Widget files
        require_once( __DIR__ . '/widgets/test-widget.php' );

        // Register widget by creating the class in the file you have created naming as test-widget.php
        \Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_Test_Widget() );

    }

    public function includes() {}

}
Elementor_Test_Extension::instance();

Теперь создайте класс в youtplugin / widgets / test-widget.php. Ссылка: Создание базовой функциональности виджета

class Elementor_Test_Widget extends \Elementor\Widget_Base
{
    /**
     * Define your core logic for the widget
     */
    public function __construct()
    {

    }
}

Остальные довольно понятны. Для категории виджетов скелет также похож. Надеюсь, это поможет.

2 голосов
/ 24 марта 2019

Создайте отдельный файл (например, helper.php) в папке вашего плагина и включите его в основной файл загрузчика плагина. вставьте следующий код в файл помощника. И это создаст отдельную категорию на боковой панели виджета Elementor.

<?php 
namespace Elementor;

function category_elementor_init(){
    Plugin::instance()->elements_manager->add_category(
        'category-for-elementor',
        [
            'title'  => 'Elementor Category',
            'icon' => 'font'
        ],
        1
    );
}
add_action('elementor/init', 'Elementor\category_elementor_init');
0 голосов
/ 24 марта 2019

Спасибо большое! Я сделал новую категорию виджетов сейчас. И я хотел бы сделать новые разделы и элементы управления.

[Проверьте следующую ссылку, пожалуйста.] [Надеюсь создать новые разделы и элементы управления]

[1]: https: cl.ly/b29f0a0b09da

0 голосов
/ 24 марта 2019

Спасибо за ваш ответ, Ахмед.Я следовал твоему шагу.Но у меня есть проблема, чтобы исправить.Я добавил следующий код, но не могу найти категорию теста.Ничего не произошло.

(test-widget.php)

/**
 * Elementor oEmbed Widget.
 *
 * Elementor widget that inserts an embbedable content into the page, from any given URL.
 *
 * @since 1.0.0
 */
class Elementor_Test_Widget extends \Elementor\Widget_Base {

    /**
     * Get widget name.
     *
     * Retrieve oEmbed widget name.
     *
     * @since 1.0.0
     * @access public
     *
     * @return string Widget name.
     */
    public function get_name() {
        return 'test';
    }

    /**
     * Get widget title.
     *
     * Retrieve oEmbed widget title.
     *
     * @since 1.0.0
     * @access public
     *
     * @return string Widget title.
     */
    public function get_title() {
        return __( 'test', 'ElementorTest' );
    }

    /**
     * Get widget icon.
     *
     * Retrieve oEmbed widget icon.
     *
     * @since 1.0.0
     * @access public
     *
     * @return string Widget icon.
     */
    public function get_icon() {
        return 'fa fa-code';
    }

    /**
     * Get widget categories.
     *
     * Retrieve the list of categories the oEmbed widget belongs to.
     *
     * @since 1.0.0
     * @access public
     *
     * @return array Widget categories.
     */
    public function get_categories() {
        return [ 'general' ];
    }

    /**
     * Register oEmbed widget controls.
     *
     * Adds different input fields to allow the user to change and customize the widget settings.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function _register_controls() {

        $this->start_controls_section(
            'content_section',
            [
                'label' => __( 'Content', 'ElementorTest' ),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'url',
            [
                'label' => __( 'URL to embed', 'ElementorTest' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'input_type' => 'url',
                'placeholder' => __( 'https://your-link.com', 'ElementorTest' ),
            ]
        );

        $this->end_controls_section();

    }

    /**
     * Render oEmbed widget output on the frontend.
     *
     * Written in PHP and used to generate the final HTML.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function render() {

        $settings = $this->get_settings_for_display();

        $html = wp_oembed_get( $settings['url'] );

        echo '<div class="test-elementor-widget">';

        echo ( $html ) ? $html : $settings['url'];

        echo '</div>';

    }

} функция add_elementor_widget_categories ($ elements_manager) {

        $elements_manager->add_category(
            'first-category',
            [
                'title' => __( 'First Category', 'ElementorTest' ),
                'icon' => 'fa fa-plug',
            ]
        );
        $elements_manager->add_category(
            'second-category',
            [
                'title' => __( 'Second Category', 'ElementorTest' ),
                'icon' => 'fa fa-plug',
            ]
        );

    }
    add_action( 'elementor/elements/categories_registered', 'add_elementor_widget_categories' );

Пожалуйста, проверьте это 1

и проверьте это тоже. 2

(ElementorTest.php)

/**
 * Plugin Name: ElementorTest
 * Plugin URI:  https://localhost:4431/wp/plugins/ElementorTest/
 * Description: Basic Elementor Extension
 * Version:     1.1
 * Author:      Ahmed Maruf
 * Author URI:  https://localhost:4431/wp/
 * Text Domain: elementortestplugin
 * Domain Path: /languages
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}



final class Elementor_Test_Extension {

        const VERSION = "1.1"; //Your plugin version
        const MINIMUM_ELEMENTOR_VERSION = "2.0.0"; //Minimum Elementor Version Required
        const MINIMUM_PHP_VERSION = "7.0"; //Minimum PHP version required to run your plugin

        private static $_instance = null;
        /*The plugin class should use a singleton design pattern to make sure it loads only once*/
        public static function instance() {
            if ( is_null( self::$_instance ) ) {
             self::$_instance = new self();
         }return self::$_instance;

     }
     /*

      The constructor should initiate the plugin. The init process should check for basic requirements and then then run the plugin logic. Note that If one of the basic plugin requirements fails the plugin logic won’t run.
      */
      public function __construct() {
        add_action( 'plugins_loaded', [ $this, 'init' ] );
    }
    /*Initialize all the basic requirements to run the plugin logic*/
    public function init() {
        load_plugin_textdomain( 'elementortestplugin' );

        // Check if Elementor installed and activated
        if ( ! did_action( 'elementor/loaded' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_missing_main_plugin' ] );
            return;
        }

        // Check for required Elementor version
        if ( ! version_compare( ELEMENTOR_VERSION, self::MINIMUM_ELEMENTOR_VERSION, '>=' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_minimum_elementor_version' ] );
            return;
        }

        // Check for required PHP version
        if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
            return;
        }

        // Add Plugin actions when rest requirements are passed
        add_action( 'elementor/widgets/widgets_registered', [ $this, 'init_widgets' ] );     

    }
    /*Callback function for the action hook admin notices*/
    public function admin_notice_missing_main_plugin() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $message = sprintf(
            /* translators: 1: Plugin name 2: Elementor */
            esc_html__( '"%1$s" requires "%2$s" to be installed and activated.', 'elementortestplugin' ),
            '<strong>' . esc_html__( 'Elementor Test Extension', 'elementortestplugin' ) . '</strong>',
            '<strong>' . esc_html__( 'Elementor', 'elementortestplugin' ) . '</strong>'
        );

        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );

    }

    /*Callback function for action hook admin notices upon elementor version not matching*/
    public function admin_notice_minimum_elementor_version() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $message = sprintf(
            /* translators: 1: Plugin name 2: Elementor 3: Required Elementor version */
            esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementortestplugin' ),
            '<strong>' . esc_html__( 'Elementor Test Extension', 'elementortestplugin' ) . '</strong>',
            '<strong>' . esc_html__( 'Elementor', 'elementortestplugin' ) . '</strong>',
            self::MINIMUM_ELEMENTOR_VERSION
        );

        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );

    }
    /*Callback function for action hood admin notices upon php version not matched*/
    public function admin_notice_minimum_php_version() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $message = sprintf(
            /* translators: 1: Plugin name 2: PHP 3: Required PHP version */
            esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'elementortestplugin' ),
            '<strong>' . esc_html__( 'Elementor Test Extension', 'elementortestplugin' ) . '</strong>',
            '<strong>' . esc_html__( 'PHP', 'elementortestplugin' ) . '</strong>',
            self::MINIMUM_PHP_VERSION
        );

        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message );

    }

    /*
    @Callback function for the action hook elementor/widgets/widgets_registered
    @Create the folder widgets and the file under you custom plugin /widgets/test-widget.php
    */
    public function init_widgets() {

        // Include Widget files
        require_once( __DIR__ . '/widgets/test-widget.php' );

        // Register widget by creating the class in the file you have created naming as test-widget.php
        \Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_Test_Widget() );

    }

    public function includes() {}

}
Elementor_Test_Extension::instance();
...