0

I have used this method to create a custom post page but I want the content to be the imported XML file content to be the content of this file. https://stackoverflow.com/a/32314726/3697484

I have the XML content as a file saved inside a plugin folder.

I am basically looking for a method to use the WordPress importer function inside an admin options page to automate the process. - User clicks on the link in the admin options page = It imports the XML page with it it's content.

I have no idea if there is a function or API to get it done. please help

No category, no tags or the custom fields are being imported.


// I am actually trying a method to import the json output from elementor / xml output of elementor page from wordpress exporter

This is where elementor converts json to a page : https://github.com/elementor/elementor/blob/master/includes/template-library/sources/local.php - line 895

public function admin_import_template_form() {
        if ( ! self::is_base_templates_screen() ) {
            return;
        }
        /** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
        $ajax = Plugin::$instance->common->get_component( 'ajax' );
        ?>
        <div id="elementor-hidden-area">
            <a id="elementor-import-template-trigger" class="page-title-action"><?php echo __( 'Import Templates', 'elementor' ); ?></a>
            <div id="elementor-import-template-area">
                <div id="elementor-import-template-title"><?php echo __( 'Choose an Elementor template JSON file or a .zip archive of Elementor templates, and add them to the list of templates available in your library.', 'elementor' ); ?></div>
                <form id="elementor-import-template-form" method="post" action="<?php echo admin_url( 'admin-ajax.php' ); ?>" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="elementor_library_direct_actions">
                    <input type="hidden" name="library_action" value="direct_import_template">
                    <input type="hidden" name="_nonce" value="<?php echo $ajax->create_nonce(); ?>">
                    <fieldset id="elementor-import-template-form-inputs">
                        <input type="file" name="file" accept=".json,application/json,.zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" required>
                        <input type="submit" class="button" value="<?php echo esc_attr__( 'Import Now', 'elementor' ); ?>">
                    </fieldset>
                </form>
            </div>
        </div>
        <?php
    }

Another method :

   private function import_single_template( $file_name ) {
            $data = json_decode( file_get_contents( $file_name ), true );
            if ( empty( $data ) ) {
                return new \WP_Error( 'file_error', 'Invalid File' );
            }
            $content = $data['content'];
            if ( ! is_array( $content ) ) {
                return new \WP_Error( 'file_error', 'Invalid File' );
            }
            $content = $this->process_export_import_content( $content, 'on_import' );
            $page_settings = [];
            if ( ! empty( $data['page_settings'] ) ) {
                $page = new Model( [
                    'id' => 0,
                    'settings' => $data['page_settings'],
                ] );
                $page_settings_data = $this->process_element_export_import_content( $page, 'on_import' );
                if ( ! empty( $page_settings_data['settings'] ) ) {
                    $page_settings = $page_settings_data['settings'];
                }
            }
            $template_id = $this->save_item( [
                'content' => $content,
                'title' => $data['title'],
                'type' => $data['type'],
                'page_settings' => $page_settings,
            ] );
            if ( is_wp_error( $template_id ) ) {
                return $template_id;
            }
            return $this->get_item( $template_id );
        }

Not sure if they use this:
    public function import_template( $name, $path ) {
        if ( empty( $path ) ) {
            return new \WP_Error( 'file_error', 'Please upload a file to import' );
        }
        $items = [];
        $file_extension = pathinfo( $name, PATHINFO_EXTENSION );
        if ( 'zip' === $file_extension ) {
            if ( ! class_exists( '\ZipArchive' ) ) {
                return new \WP_Error( 'zip_error', 'PHP Zip extension not loaded' );
            }
            $zip = new \ZipArchive();
            $wp_upload_dir = wp_upload_dir();
            $temp_path = $wp_upload_dir['basedir'] . '/' . self::TEMP_FILES_DIR . '/' . uniqid();
            $zip->open( $path );
            $valid_entries = [];
            // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
            for ( $i = 0; $i < $zip->numFiles; $i++ ) {
                $zipped_file_name = $zip->getNameIndex( $i );
                $zipped_extension = pathinfo( $zipped_file_name, PATHINFO_EXTENSION );
                if ( 'json' === $zipped_extension ) {
                    $valid_entries[] = $zipped_file_name;
                }
            }
            if ( ! empty( $valid_entries ) ) {
                $zip->extractTo( $temp_path, $valid_entries );
            }
            $zip->close();
            $file_names = array_diff( scandir( $temp_path ), [ '.', '..' ] );
            foreach ( $file_names as $file_name ) {
                $full_file_name = $temp_path . '/' . $file_name;
                $import_result = $this->import_single_template( $full_file_name );
                unlink( $full_file_name );
                if ( is_wp_error( $import_result ) ) {
                    return $import_result;
                }
                $items[] = $import_result;
            }
            rmdir( $temp_path );
        } else {
            $import_result = $this->import_single_template( $path );
            if ( is_wp_error( $import_result ) ) {
                return $import_result;
            }
            $items[] = $import_result;
        }
        return $items;
    }

Any possibility of replicating this process?

Json Export :

    { 
   "version":"0.4",
   "title":"Export Template",
   "type":"page",
   "content":[ 
      { 
         "id":"1f161830",
         "settings":{ 
            "content_width":{ 
               "unit":"px",
               "size":"980"
            },
            "custom_height":{ 
               "unit":"px",
               "size":"120"
            },
            "content_position":"middle",
            "structure":"20",
            "background_background":"classic",
            "background_color":"#003e53",
            "padding":{ 
               "unit":"px",
               "top":"0",
               "right":"0",
               "bottom":"30",
               "left":"0",
               "isLinked":false
            },
            "padding_tablet":{ 
               "unit":"px",
               "top":"0",
               "right":"20",
               "bottom":"0",
               "left":"20",
               "isLinked":false
            },
            "padding_mobile":{ 
               "unit":"px",
               "top":"30",
               "right":"30",
               "bottom":"30",
               "left":"30",
               "isLinked":true
            }
         },
         "elements":[ 
            { 
               "id":"4c55a461",
               "settings":{ 
                  "_column_size":50,
                  "_inline_size":"64.388",
                  "padding":{ 
                     "unit":"px",
                     "top":"0",
                     "right":"0",
                     "bottom":"0",
                     "left":"0",
                     "isLinked":false
                  }
               },
               "elements":[ 
                  { 
                     "id":"7c41176b",
                     "settings":{ 
                        "title":"Your Dream Vacation is Here",
                        "header_size":"h3",
                        "align_mobile":"center",
                        "title_color":"#ffffff",
                        "typography_typography":"custom",
                        "typography_font_size":{ 
                           "unit":"px",
                           "size":36
                        },
                        "typography_font_size_mobile":{ 
                           "unit":"px",
                           "size":32
                        },
                        "typography_font_family":"Roboto",
                        "typography_font_weight":"300"
                     },
                     "elements":[ 

                     ],
                     "isInner":false,
                     "widgetType":"heading",
                     "elType":"widget"
                  }
               ],
               "isInner":false,
               "elType":"column"
            },
            { 
               "id":"528d240a",
               "settings":{ 
                  "_column_size":50,
                  "_inline_size":"35.613"
               },
               "elements":[ 
                  { 
                     "id":"79cddb6",
                     "settings":{ 
                        "text":"Book A Room",
                        "align":"right",
                        "align_mobile":"center",
                        "size":"lg",
                        "icon":"fa fa-angle-double-right",
                        "icon_align":"right",
                        "typography_typography":"custom",
                        "typography_font_size_tablet":{ 
                           "unit":"px",
                           "size":"15"
                        },
                        "typography_font_family":"Playfair Display",
                        "background_color":"#e4bc36",
                        "button_background_hover_color":"#8daca6",
                        "border_radius":{ 
                           "unit":"px",
                           "top":"0",
                           "right":"0",
                           "bottom":"0",
                           "left":"0",
                           "isLinked":true
                        }
                     },
                     "elements":[ 

                     ],
                     "isInner":false,
                     "widgetType":"button",
                     "elType":"widget"
                  }
               ],
               "isInner":false,
               "elType":"column"
            }
         ],
         "isInner":false,
         "elType":"section"
      },
      { 
         "id":"8ffa3fa",
         "settings":{ 
            "content_width":{ 
               "unit":"px",
               "size":"980"
            },
            "content_position":"middle",
            "structure":"20",
            "padding":{ 
               "unit":"px",
               "top":"80",
               "right":"0",
               "bottom":"0",
               "left":"0",
               "isLinked":false
            },
            "padding_tablet":{ 
               "unit":"px",
               "top":"60",
               "right":"30",
               "bottom":"30",
               "left":"30",
               "isLinked":false
            },
            "reverse_order_mobile":"reverse-mobile"
         },
         "elements":[ 
            { 
               "id":"a721fd6",
               "settings":{ 
                  "_column_size":50,
                  "_inline_size":null,
                  "padding":{ 
                     "unit":"px",
                     "top":"0",
                     "right":"60",
                     "bottom":"0",
                     "left":"0",
                     "isLinked":false
                  },
                  "padding_mobile":{ 
                     "unit":"px",
                     "top":"0",
                     "right":"0",
                     "bottom":"0",
                     "left":"0",
                     "isLinked":false
                  }
               },
               "elements":[ 
                  { 
                     "id":"452fa18b",
                     "settings":{ 
                        "title":"Enjoy Some You-Time",
                        "header_size":"h3",
                        "align_mobile":"center",
                        "title_color":"#8daca6",
                        "typography_typography":"custom",
                        "typography_font_size":{ 
                           "unit":"px",
                           "size":36
                        },
                        "typography_font_family":"Playfair Display",
                        "typography_font_weight":"normal"
                     },
                     "elements":[ 

                     ],
                     "isInner":false,
                     "widgetType":"heading",
                     "elType":"widget"
                  },
                  { 
                     "id":"3c932056",
                     "settings":{ 
                        "editor":"<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.<\/p>",
                        "align_mobile":"center",
                        "typography_typography":"custom",
                        "typography_font_family":"Roboto"
                     },
                     "elements":[ 

                     ],
                     "isInner":false,
                     "widgetType":"text-editor",
                     "elType":"widget"
                  },
                  { 
                     "id":"2ae50433",
                     "settings":{ 
                        "text":"Read More",
                        "align":"left",
                        "align_mobile":"center",
                        "size":"md",
                        "icon":"fa fa-angle-double-right",
                        "icon_align":"right",
                        "typography_typography":"custom",
                        "typography_font_family":"Playfair Display",
                        "background_color":"#e4bc36",
                        "button_background_hover_color":"#8daca6",
                        "border_radius":{ 
                           "unit":"px",
                           "top":"0",
                           "right":"0",
                           "bottom":"0",
                           "left":"0",
                           "isLinked":true
                        }
                     },
                     "elements":[ 

                     ],
                     "isInner":false,
                     "widgetType":"button",
                     "elType":"widget"
                  }
               ],
               "isInner":false,
               "elType":"column"
            },
            { 
               "id":"169d14c2",
               "settings":{ 
                  "_column_size":50,
                  "_inline_size":null
               },
               "elements":[ 
                  { 
                     "id":"41d9ad60",
                     "settings":{ 
                        "image":{ 
                           "id":591,
                           "url":"http:\/\/demo.geekygreenowl.com\/wp-content\/uploads\/2019\/11\/main2.jpg"
                        },
                        "image_size":"full",
                        "image_border_border":"solid",
                        "image_border_width":{ 
                           "unit":"px",
                           "top":"10",
                           "right":"10",
                           "bottom":"10",
                           "left":"10",
                           "isLinked":true
                        },
                        "image_border_color":"#ffffff",
                        "image_box_shadow_box_shadow_type":"yes",
                        "image_box_shadow_box_shadow":{ 
                           "horizontal":"10",
                           "vertical":"10",
                           "blur":"20",
                           "spread":0,
                           "inset":"",
                           "color":"rgba(0,0,0,0.12)"
                        },
                        "_padding_mobile":{ 
                           "unit":"px",
                           "top":"0",
                           "right":"0",
                           "bottom":"30",
                           "left":"0",
                           "isLinked":false
                        }
                     },
                     "elements":[ 

                     ],
                     "isInner":false,
                     "widgetType":"image",
                     "elType":"widget"
                  }
               ],
               "isInner":false,
               "elType":"column"
            }
         ],
         "isInner":false,
         "elType":"section"
      }
   ]
}
  • You need to hire a dev to do this. – meevly.com Nov 5 '19 at 6:28
  • @meevly.com surely that doesn't make an answer :). I haven't asked any to do the job for me. I am only looking for a method. Thanks for your suggestion! – Latheesh V M Villa Nov 5 '19 at 6:44
  • can you add an example snippet of XML or JSON you trying to import... – Kudratullah Nov 6 '19 at 8:15
  • @Kudratullah I have added JSON file to question and the place where elementor coverts this JSON file – Latheesh V M Villa Nov 6 '19 at 13:17
1
+50

So, are you looking for a JSON importer for Elementor? If so, why not use their native importer? See here:

Native Elementor Importer

However, if you would rather have an option in a menu, try this small plugin. It adds an importer under Tools > Import, called Elementor JSON Importer, that you can use to import JSON files (it technically also handles .zip files). With it, you can upload a JSON file and it generates an Elementor template from it. It saves the uploaded files in the wp-content/uploads folder.

<?php
/**
 * Elementor JSON Importer
 *
 * Plugin Name: Elementor Importer
 * Plugin URI:  https://example.com
 * Description: Imports local JSON data and creates an Elementor post.
 * Version:     0.1.0
 * Author:      Your Name Here
 * Author URI:  https://example.com
 * Text Domain: elementor-json-importer
 */

if ( ! defined( 'WP_LOAD_IMPORTERS' ) )
    return;

// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';

// Require Elementor API
require_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/base.php';
require_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/local.php';

// Make sure the importer class exists and is available.
if ( ! class_exists( 'WP_Importer' ) ) {
    $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
    if ( file_exists( $class_wp_importer ) ) {
        require_once $class_wp_importer;
    }
}

/**
 * Elementor JSON Importer
 *
 * Will process JSON data for importing Elementor posts into WordPress.
 *
 * @since 0.1.0
 */
if ( class_exists( 'WP_Importer' ) ) {

    class Elementor_JSON_Importer extends WP_Importer {

        // Constructor
        public function __construct() {
            // Nothing.
        }

        // Executes on import dispatch.
        public function dispatch() {
            if ( empty( $_GET['step'] ) ) {
                $step = 0;
            } else {
                $step = (int) $_GET['step'];
            }

            $this->header();

            switch ($step) {
                case 0:
                    $this->greet();
                    break;
                case 1:
                    check_admin_referer( 'import-upload' );
                    $result = $this->import();
                    if ( is_wp_error( $result ) ) {
                        echo $result->get_error_message();
                    }
                    break;
            }

            $this->footer();
        }

        // Echoes page footer.
        protected function footer() {
            echo '</div>';
        }

        // Echoes greeting.
        protected function greet() {
            echo '<div class="narrow">';
            echo '<p>'.__( 'This importer allows you to extract posts from an Elementor JSON file into your WordPress site. Pick a JSON file to upload and click Import.', 'elementor-json-importer' ).'</p>';
            wp_import_upload_form( 'admin.php?import=elementor-json&amp;step=1' );
            echo '</div>';
        }

        // Echoes page header.
        protected function header() {
            echo '<div class="wrap">';
            screen_icon();
            echo '<h2>'.__( 'Import JSON', 'elementor-json-importer-importer' ).'</h2>';
        }

        // Performs the actual import by using methods of the Elementor API.
        protected function import() {
            $error = new WP_Error();
            $file = wp_import_handle_upload();

            if ( isset( $file['error'] ) ) {
                $error->add( 'upload-error', $file['error'] );
                return $error;
            }

            $source_local = new Elementor\TemplateLibrary\Source_Local();
            if ( ! method_exists( $source_local, 'import_template' ) ) {
                $error->add( 'elementor-api-error', __( 'Elementor API unavailable.', 'elementor-json-importer' ) );
                return $error;
            }

            try {
                $result = $source_local->import_template( basename( $file['file'] ), $file['file'] );
            } catch ( Exception $e ) {
                $error->add( 'elementor-import-error', __( 'Elementor import has failed.', 'elementor-json-importer' ) );
                return $error;
            } finally {
                wp_import_cleanup( $file['id'] );
            }

            echo '<h3>';
            printf( __( 'All done. <a href="%s">View template</a>', 'rss-importer' ), esc_url( $result[0]['url'] ) );
            echo '</h3>';
        }
    }

    // Create a new instance of the importer class.
    $elementor_json_importer = new Elementor_JSON_Importer();

    // Attempt to register importer.
    $error = register_importer(
        'elementor-json',
        __( 'Elementor JSON Importer', 'elementor-json-importer' ),
        __( 'Import posts from an Elementor JSON file.', 'elementor-json-importer' ),
        array ( $elementor_json_importer, 'dispatch' )
    );

    if ( is_wp_error( $error ) ) {
        error_log( $error->get_error_message() );
    }   

} // class_exists( 'WP_Importer' )

function elementor_json_importer_init() {
    load_plugin_textdomain( 'elementor-json-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
add_action( 'init', 'elementor_json_importer_init' );

It depends heavily on the Elementor plugin, though, so make sure to check if it works each time the Elementor plugin receives an update.

  • And if you are still looking for an XML importer, you could start from here and write that yourself. – Cas Dekkers Nov 8 '19 at 13:03
  • Wow, that really helps!. If possible I would kindly request an addition, will it be possible to automate the tool? Say a button in the admin triggers this tool and looks for the JSON files provided in the folder then import it. I think the ajax button will do the trick? But I don't know the method to trigger this tool? I think this method can be a really good way of allowing the developer to share their templates. – Latheesh V M Villa Nov 8 '19 at 13:25
  • Just so I get the bigger picture, why exactly do you prefer that specific functionality over an upload? Besides skipping the upload step, what do you gain? – Cas Dekkers Nov 8 '19 at 13:43
  • Hi, Elementor has not provided any APIs to add templates created by a developer. wordpress.org/plugins/elementskit-lite, crocoblock.com/plugins/jetelements they have a method but it's complex, also wp remote request is also needed. Elementor users are used to just click and import the templates so if this method works it becomes easy to share templates. – Latheesh V M Villa Nov 8 '19 at 13:56
1

So if I understand your question correctly, you have an XML file, and you would like to import it and save the content to a post?

You can do this with a plugin, for example, this one, but if you're not too keen on third-party plugins, you could try parsing the XML yourself with PHP's SimpleXML parser. Here's an example from w3schools.com. With it, you can turn your XML data into PHP objects. To my knowledge, there exists no built-in WP API that you can use for this purpose.

Does this answer your question?

  • Please check the question again. I have added more data. Thanks :) – Latheesh V M Villa Nov 7 '19 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.