<?php
/**
* Elementor template importer.
*
* Saves the generated Elementor JSON as a WordPress post of type
* 'elementor_library', making it available in Elementor's
* Templates → Saved Templates panel.
*/
if ( ! defined( 'ABSPATH' ) ) exit;
class FTE_Template_Importer {
/**
* Import an Elementor template into WordPress.
*
* @param array $template The Elementor template (with 'content' key).
* @param string $title Template title.
* @return int|WP_Error Post ID on success.
*/
public function import( array $template, string $title = 'Imported from Figma' ) {
// Check that Elementor is active
if ( ! did_action( 'elementor/loaded' ) ) {
return new WP_Error( 'elementor_missing', 'Elementor plugin is not active.' );
}
// Create the template post
$post_id = wp_insert_post( [
'post_title' => sanitize_text_field( $title ),
'post_status' => 'publish',
'post_type' => 'elementor_library',
], true );
if ( is_wp_error( $post_id ) ) {
return $post_id;
}
// Set template type taxonomy
wp_set_object_terms( $post_id, 'page', 'elementor_library_type' );
// Save the Elementor data
// Elementor reads from _elementor_data (JSON string) and _elementor_edit_mode
// IMPORTANT: wp_slash() is required — update_post_meta runs wp_unslash() internally,
// which would strip the \" escapes from json_encode and corrupt the JSON.
update_post_meta( $post_id, '_elementor_data', wp_slash( wp_json_encode( $template['content'] ) ) );
update_post_meta( $post_id, '_elementor_edit_mode', 'builder' );
update_post_meta( $post_id, '_elementor_template_type', 'page' );
update_post_meta( $post_id, '_elementor_version', '3.0.0' );
// Store page settings if any
if ( ! empty( $template['page_settings'] ) ) {
// Normalize: Elementor's Controls_Stack::sanitize_settings() requires an array.
// Upstream JSON may have been decoded as stdClass (json_decode without assoc=true),
// which WP would serialize verbatim and later trip a TypeError in the editor.
$ps = $template['page_settings'];
if ( is_object( $ps ) ) {
$ps = json_decode( wp_json_encode( $ps ), true );
}
update_post_meta( $post_id, '_elementor_page_settings', is_array( $ps ) ? $ps : array() );
}
// Mark as imported from Figma (for our own tracking)
update_post_meta( $post_id, '_fte_imported', true );
update_post_meta( $post_id, '_fte_import_date', current_time( 'mysql' ) );
// Clear Elementor CSS cache for this post so it regenerates
if ( class_exists( '\Elementor\Plugin' ) ) {
$css_file = \Elementor\Core\Files\CSS\Post::create( $post_id );
if ( $css_file ) {
$css_file->delete();
}
}
return $post_id;
}
}