我有一个自定义post类型,它有一个标题,两个元框自定义字段
$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 "";
echo "";
echo "To insert the posts into the database, click the button to the right.";
echo "Insert Posts";
echo "";
echo "";
});
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"
));
}
});发布于 2018-08-30 16:25:38
您的metas需要作为数组传递给wp_insert_post(),如下所示:
// Insert the post into the database
$post["id"] = wp_insert_post( array(
"post_title" => $post["title"],
"post_type" => $cpt["custom-post-type"],
"meta_input" => array(
"custom-field-1" =>$cpt["custom-field-1"],
"custom-field-2" =>$cpt["custom-field-2"],
)
"post_status" => "publish"
));https://developer.wordpress.org/reference/functions/wp_插入_post/#参数
https://wordpress.stackexchange.com/questions/312917
复制相似问题