How import XML data into WordPress programatically?

WordPress offers an easy way to import and export its data using XML. It’s done with a GUI-based built-in importer. What I’d like to do however, is to be able to import certain XML files from within my theme (upon activation or after executing a function).

My case:
While there are a few plugins that can create dummy content for you, I couldn’t find any way to do what I’m trying to do – import a set of ACF fields stored in XML file.

Read More

Is there any way to do it?

Related posts

Leave a Reply

1 comment

  1. Update: This function is meant to deal with XML data and is limited to ACF up to version 4. ACF 5 exports its fields as JSON data.

    The solution turned into a WordPress plugin.

    Here’s the solution to my problem.

    function insert_acf_field( $xml_string, $allow_duplicates = false ) {
    
    // Parse ACF post's XML
    $content = simplexml_load_string( $xml_string, 'SimpleXMLElement', LIBXML_NOCDATA); 
    
    // Parse XML post attributes containing fields
    $wp_post_attributes = $content->channel->item->children('wp', true);
    
    # Copy basic properties from the exported field
    $wp_post_data = array(
        'post_type'   => 'acf',
        'post_title'  => $content->channel->item->title,
        'post_name'   => $wp_post_attributes->post_name,
        'post_status' => 'publish',
        'post_author' => 1
    
    );
    
    $the_post = get_page_by_title($content->channel->item->title, 'OBJECT', 'acf');
    
    # Execute only if doesn't exist already
    if ( !$the_post || $allow_duplicates == true ) {
        $post_id = wp_insert_post( $wp_post_data );
    }
    else {
        $post_id = $the_post->ID;
    }
    
    $wp_post_meta = $content->channel->item->children('wp', true);
    
    if( $wp_post_meta ) {
        foreach ( $wp_post_meta as $row) {
    
            // Choose only arrays (postmeta)
            if( count($row) > 0) {
                // using addlashes on meta values to compensate for stripslashes() that will be run upon import
                update_post_meta( $post_id, $row->meta_key, addslashes( $row->meta_value ) );
            }
    
        }
    }
    }
    

    Here’s how to use it:

    Function expects at least $xml_string parameter to be passed. It should contain the contents of the XML file that is produced by ACF plugin upon export of an ACF field (post of acf type).

    The function will try to create one new ACF post unless one already exists, and then populate it with fields. To insert more than one field (a clone) with the same title, you should pass true as a second parameter.

    There are a few issues still to be addressed, but the function in its current state should be usable