Import Posts from CSV Data

Import Posts from Custom CSV Data:

https://www.sitepoint.com/programmatically-creating-wordpress-posts-from-csv-data/

Example for CPT and ACF fields:


/**
 * Show 'insert posts' button on backend
 */
add_action( "admin_notices", function() {
    echo "<div class='updated'>";
    echo "<p>";
    echo "To insert or overwrite the posts into the CSV files, click the button to the right.";
    echo "<a class='button button-primary' style='margin:0.25em 1em' href='{$_SERVER["REQUEST_URI"]}&insert_km_products'>Import products from CSV</a>";
    echo "</p>";
    echo "</div>";
});

/**
 * Create and insert posts from CSV files
 */
add_action( "admin_init", function() {

    //  the post creation _only_ happens when you want it to.
    if ( ! isset( $_GET["insert_km_products"] ) ) {
        return;
    }

    // Change these to whatever you set
    $custom_names = array(
        "custom-post-type" => "produkte"
    );

    // Get the data from all those CSVs!
    $posts = function() {
        $data = array();
        $errors = array();
        $uploads = wp_upload_dir();
        $upload_path = $uploads['basedir'];

        // Get array of CSV files
        $files = glob( $upload_path."/km_csv/*.csv" );

        foreach ( $files as $file ) {

            // Attempt to change permissions if not readable
            if ( ! is_readable( $file ) ) {
                chmod( $file, 0744 );
            }

            // Check if file is writable, then open it in 'read only' mode
            if ( is_readable( $file ) && $_file = fopen( $file, "r" ) ) {
                $path_parts = pathinfo($file);

                // To sum this part up, all it really does is go row by row, column by column, saving all the data
                $post = array();

                // Get first row in CSV, which is of course the headers
                $header = fgetcsv( $_file, 0, "\t" );

                while ( $row = fgetcsv( $_file, 0, "\t" ) ) {

                    foreach ( $header as $i => $key ) {
                        $post[$key] = $row[$i];
                    }
                    
                    $post['filename'] = $path_parts['filename'];
                    $data[] = $post;
                    
                    // break; // only 1
                }

                fclose( $_file );

            } else {
                $errors[] = "File '$file' could not be opened. Check the file's permissions to make sure it's readable by your server.";
            }
        }

        if ( ! empty( $errors ) ) {
            // ... do stuff with the errors
        }

        return $data;
    };


    //  Check to see if the current post exists within the    
    $post_exists = function( $shop, $id, $import_post_type ) use ( $custom_names ) {
        $product_post = new WP_Query(
            array(
                'post_type'         => $import_post_type,
                'post_status '      => 'publish',
                'meta_query' => array(
                    array(
                        'key'     => 'shop',
                        'value'   => $shop,
                        // 'value'   => 'test',
                    ),
                    array(
                        'key'     => 'id',
                        'value'   => $id,
                    ),
                ),
            )
        );

        return $product_post->post->ID;
    };


    /**
     * IMPORT into post type
     */
    foreach ( $posts() as $post ) {

        $import_post_type = 'produkte';
        $import_taxonomy = 'kategorie';

        switch ($post['filename']) {
            case 'hubmann':
                $product_link = 'http://shop.hubmann-leibnitz.at/';
                break;
            case 'groebner':
                $product_link = 'https://shop.groebner.eu/';
                break;
            case 'blumenversand':
                $product_link = 'https://www.blumenversand.at/';
                break;
            case 'ma-chic':
                $product_link = 'https://shop.ma-chic.at/';
                break;
            default:
                $product_link = $post['Link'];
                break;
        }


        // If the post exists, skip this post and go to the next one
        if ( $existing_post_id = $post_exists( $post["filename"], $post['Id'], $import_post_type ) ) {

            wp_insert_post( array(
                'ID' => $existing_post_id,
                'post_title' => $post['Title'],
                'post_type' => $import_post_type,
                'post_status' => 'publish'
            ));

            $post['post_id'] = $existing_post_id;

        } else {
            // Insert the post into the database
            $post['post_id'] = wp_insert_post( array(
                'post_title' => $post['Title'],
                'post_type' => $import_post_type,
                'post_status' => 'publish'
            ));
        }

        update_field( 'condition', $post['Condition'], $post['post_id'] );
        update_field( 'price', $post['Price'], $post['post_id'] );
        update_field( 'availability', $post['Availability'], $post['post_id'] );
        update_field( 'image_link', $post['Image_Link'], $post['post_id'] );
        update_field( 'category', $post['Category'], $post['post_id'] );
        update_field( 'id', $post['Id'], $post['post_id'] );
        update_field( 'link', $product_link, $post['post_id'] );
        update_field( 'description', $post['Description'], $post['post_id'] );
        update_field( 'gtin', $post['GTIN'], $post['post_id'] );
        update_field( 'brand', $post['Brand'], $post['post_id'] );
        update_field( 'shipping_weight', $post['Shipping_weight'], $post['post_id'] );
        update_field( 'shop', $post['filename'], $post['post_id'] );


        //Assign 'Kategorie' taxonomy
        $args = array(
            'hide_empty' => false,
            'taxonomy'  => $import_taxonomy,
            'meta_query' => array(
                array(
                   'key'       => 'km_id',
                   'value'     => $post['Category'],
                   'compare'   => '='
                )
            ),
            );
        $terms = get_terms( $args );
    
        wp_delete_object_term_relationships( $post['post_id'], $import_taxonomy ); // remove all terms 
        
        if($terms) {
            wp_set_object_terms( $post['post_id'], $terms[0]->term_id, $import_taxonomy ); // assign new terms
        }
    }

});