首页 > 解决方案 > 构建自定义 Elementor Widget-Wordpress

问题描述

我想创建一个 elementor 小部件并将其添加到基本 elementor 菜单中。我根据本教程找到并执行此操作,但它不起作用(未出现在基本菜单中): https ://develowp.com/build-a-custom-elementor-widget/ 在此处输入图像描述。我使用调试,我认为原因可能是这段代码:“add_action('elementor/widgets/widgets_registered', [$this, 'register_widgets']);” 任何人都可以帮我解决这个问题或任何其他代码运行正确吗?

标签: wordpresselementor

解决方案


**创建自定义 Elementor 小部件与创建原生 WordPress 小部件没有太大区别,您基本上首先创建一个扩展 Widget_Base 类的类并填写所有必需的方法。

每个小部件都需要一些基本设置,例如在代码中标识小部件的唯一名称、用作小部件标签的标题和图标。除此之外,我们还有一些高级设置,例如小部件控件(基本上是用户选择自定义数据的字段),以及根据小部件控件的用户数据生成最终输出的渲染脚本。**

<?php
/**
* Elementor oEmbed Widget.
*
* Elementor widget that inserts an embbedable content into the page, from 
any given URL.
*
* @since 1.0.0
*/
class Elementor_oEmbed_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 'oembed';
}

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

/**
 * 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', 'plugin-name' ),
            'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
        ]
    );

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

    $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="oembed-elementor-widget">';

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

    echo '</div>';

 }

}

推荐阅读