You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在WordPress的Elementor页面中入队自定义JavaScript?

问题描述

我正在开发一个WordPress网站,只有部分页面用Elementor构建,不是全站都用。我想只在Elementor页面加载一个小型自定义JavaScript文件,避免脚本在所有页面全局加载。目前我可以用wp_enqueue_script()来入队脚本,但不确定检测当前页面是否使用Elementor的最安全方式。有没有可靠的WordPress/Elementor判断条件,还是需要在入队前手动检查文章元数据?我有个示例思路如下,想知道推荐的实现方案是什么?

function my_custom_elementor_script() {
    if ( /* current page uses Elementor */ ) {
        wp_enqueue_script(
            'my-custom-script',
            get_stylesheet_directory_uri() . '/js/custom.js',
            array('jquery'),
            '1.0',
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'my_custom_elementor_script');

推荐实现方案

Elementor官方提供了稳定的检测方法,比手动查元数据更可靠,毕竟官方函数会适配版本更新的内部逻辑。下面是两种实用方案:

方案1:适配所有Elementor版本(含旧版)

通过检查文章元数据+排除后台场景,覆盖前端已发布的Elementor页面:

function my_custom_elementor_script() {
    // 后台页面直接跳过,避免无效加载
    if ( is_admin() ) {
        return;
    }

    global $post;
    // 确认当前页面存在,且标记为Elementor构建
    if ( $post && get_post_meta( $post->ID, '_elementor_edit_mode', true ) ) {
        wp_enqueue_script(
            'my-custom-script',
            get_stylesheet_directory_uri() . '/js/custom.js',
            array('jquery'),
            '1.0',
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'my_custom_elementor_script');

方案2:Elementor 3.0+ 简化版

如果你的Elementor版本在3.0及以上,可以直接用官方提供的is_elementor_page()函数,同时覆盖前端和编辑模式:

function my_custom_elementor_script() {
    // 先确认函数存在,再判断是否为Elementor页面
    if ( function_exists('is_elementor_page') && is_elementor_page() ) {
        wp_enqueue_script(
            'my-custom-script',
            get_stylesheet_directory_uri() . '/js/custom.js',
            array('jquery'),
            '1.0',
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'my_custom_elementor_script');

关键注意点

  • 优先用官方函数,避免硬编码元数据键名(比如_elementor_edit_mode),防止Elementor版本更新后失效。
  • 加上is_admin()判断能减少后台不必要的脚本加载,优化性能。

内容的提问来源于stack exchange,提问作者Kotler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 07:20:37