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

如何通过WP Rest API获取Elementor自定义模板数据

配置WordPress REST API获取Elementor自定义模板数据

要实现通过https://localhost/wp-json/template-manager/v1/[模板ID]获取指定格式的Elementor模板数据,只需在主题的functions.php中添加以下代码,分两步完成路由注册和数据获取:

1. 注册自定义REST路由

首先注册符合需求的API路由,指定请求方式、回调函数和权限验证:

add_action('rest_api_init', 'register_template_manager_route');

function register_template_manager_route() {
    register_rest_route(
        'template-manager/v1',
        '/(?P<template_id>\d+)',
        array(
            'methods' => WP_REST_Server::READABLE, // 仅允许GET请求
            'callback' => 'get_elementor_template_data',
            'permission_callback' => function() {
                // 按需设置权限,例如仅允许管理员访问:current_user_can('manage_options')
                // 测试阶段可暂时返回true,上线后务必调整为合适权限
                return true;
            }
        )
    );
}

2. 编写模板数据回调函数

回调函数负责验证模板有效性、提取Elementor模板的标题、类型和内容,并返回指定格式的JSON:

function get_elementor_template_data($request) {
    $template_id = $request->get_param('template_id');
    
    // 验证模板是否存在且为Elementor模板
    $template_post = get_post($template_id);
    if (!$template_post || $template_post->post_type !== 'elementor_template') {
        return new WP_Error('invalid_template', '无效的Elementor模板ID', array('status' => 404));
    }
    
    // 获取Elementor模板类型(如section、page、header等)
    $template_type = get_post_meta($template_id, '_elementor_template_type', true);
    
    // 获取Elementor存储的JSON内容并解析为数组
    $elementor_raw_content = get_post_meta($template_id, '_elementor_data', true);
    $parsed_content = json_decode($elementor_raw_content, true) ?: array();
    
    // 构造响应数据
    return rest_ensure_response(array(
        'title' => get_the_title($template_id),
        'type' => $template_type ?: 'unknown',
        'content' => $parsed_content
    ));
}

关键说明

  • 权限控制:permission_callback中的权限逻辑务必根据实际需求调整,避免未授权用户获取敏感模板数据。
  • 错误处理:若请求的ID对应内容不是Elementor模板或不存在,API会返回404错误及提示信息。
  • 数据字段说明:
    • title:直接调用get_the_title获取模板的标题
    • type:从Elementor的元数据_elementor_template_type中提取模板类型
    • content:解析Elementor存储在_elementor_data中的JSON结构,转为数组返回

完成以上配置后,访问https://localhost/wp-json/template-manager/v1/123(将123替换为实际的Elementor模板ID),即可得到你需要的格式的响应数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:17:29