I have a custom post type which has one Title, and two meta box custom fields as
$price = isset( $we_productMetas['price_box'] ) ? esc_attr( $we_productMetas['price_box'][0] ) : '';
$color = isset( $we_productMetas['color_box'] ) ? esc_attr( $we_productMetas['color_box'][0] ) : '';
and I have some data in a CSV file in this format
title,price,color
Item1,50,red
Item2,20,green
Item3,60,red
Item4,10,blue
Using following code I am able to load the title
of the post properly and publish the CSV but I am missing the price
and color
metadada
Can you please take a look at this demo and let me know what I am doing wrong at
$post["id"] = wp_insert_post( array(
"post_title" => $post["title"],
"post_type" => $cpt["custom-post-type"],
"custom-field-1" =>$cpt["custom-field-1"],
"custom-field-2" =>$cpt["custom-field-2"],
"post_status" => "publish"
));
Here is the entire code
add_action( "admin_notices", function() {
echo "<div class='updated'>";
echo "<p>";
echo "To insert the posts into the database, click the button to the right.";
echo "<a class='button button-primary' style='margin:0.25em 1em' href='{$_SERVER["REQUEST_URI"]}&insert_cpt_posts'>Insert Posts</a>";
echo "</p>";
echo "</div>";
});
add_action( "admin_init", function() {
global $wpdb;
if ( ! isset( $_GET["insert_cpt_posts"] ) ) {
return;
}
$cpt = array(
"custom-field-1" => "price_box",
"custom-field-2" => "color_box",
"custom-post-type" => "women_eyeglasses"
);
$posts = function() {
$data = array();
$errors = array();
// Get array of CSV files
$files = glob( __DIR__ . "/*.csv" );
foreach ( $files as $file ) {
if ( is_readable( $file ) && $_file = fopen( $file, "r" ) ) {
$post = array();
$header = fgetcsv( $_file );
while ( $row = fgetcsv( $_file ) ) {
foreach ( $header as $i => $key ) {
$post[$key] = $row[$i];
}
$data[] = $post;
}
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 ) ) {
}
return $data;
};
$post_exists = function( $title ) use ( $wpdb, $cpt ) {
$posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = '{$cpt["custom-post-type"]}'" );
return in_array( $title, $posts );
};
foreach ( $posts() as $post ) {
if ( $post_exists( $post["title"] ) ) {
continue;
}
// Insert the post into the database
$post["id"] = wp_insert_post( array(
"post_title" => $post["title"],
"post_type" => $cpt["custom-post-type"],
"custom-field-1" =>$cpt["custom-field-1"],
"custom-field-2" =>$cpt["custom-field-2"],
"post_status" => "publish"
));
}
});