我有一个自定义帖子类型,它有一个标题和两个元框自定义字段
$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] ) : \'\';
我在CSV文件中有一些数据是这种格式的
title,price,color
Item1,50,red
Item2,20,green
Item3,60,red
Item4,10,blue
使用以下代码,我能够加载
title
并发布CSV,但我缺少
price
和
color
元数据
你能看一下这个演示并告诉我我做错了什么吗
$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"
));
这是全部代码
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"
));
}
});