更新日期:2023-07-31

免費版的 Elementor 小工具不多樣,有時候選了某個小工具後,發現控制項比較少樣,無法符合我們的需求,因此我們可以透過 action hook 去增加控制項。

對特定小工具,官方有提供 4 個 action hook,如下:

elementor/element/{$stack_name}/{$section_id}/before_section_start
elementor/element/{$stack_name}/{$section_id}/after_section_start
elementor/element/{$stack_name}/{$section_id}/before_section_end
elementor/element/{$stack_name}/{$section_id}/after_section_end

Hook 用法

add_action( 'elementor/element/icon-box/section_style_icon/before_section_end', 'add_my_control' , 10, 2 );
public function add_my_control( $element, $args ) {
    $element->add_responsive_control(
        'icon_box_margin',
        [
            'label'      => __( 'Margin', 'elementor' ),
            'type'       => \Elementor\Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', 'em', '%' ],
            'selectors'  => [
                '{{WRAPPER}} .elementor-icon-box-icon' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            ],
        ]
    );
}

程式說明

add_action( 'elementor/element/icon-box/section_style_icon/before_section_end', 'add_my_control' , 10, 2 );

這個 action 有兩傳入兩個變數,第一個是 $elmentor,第二個是 $args。而 Elementor 的 action 名稱命名比較不一樣,用 / 來區隔的落落長。

從上面程式碼裡面可以看到第三段 icon-box,它代表是 $stack_name。我們可以打開小工具的程式碼,查 get_name() 的返回值。第四段 section_style_icon 代表是 $section_id,一樣查程式碼裡面的 start_controls_section() 的 id 設定就可以得知。

$element->add_responsive_control(
    'icon_box_margin',
    [
        'label'      => __( 'Margin', 'elementor' ),
        'type'       => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => [ 'px', 'em', '%' ],
        'selectors'  => [
            '{{WRAPPER}} .elementor-icon-box-icon' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
    ]
);

然後新的控制項寫法就跟原先控制項寫法一樣,$this->add_control 的 $this 改用傳入的 $element,$this->add_responsive_control 也一樣。