how to add post_meta data to a newly created post – by csv import?
-
Hi, using 2.92, haven’t upgraded to 3.0 yet. still building out custom site….. but expect this to work with current version.
I have created a CSV importer for my site, it reads in a text file, and is formatted basically as
ID, post title, post content, post tags, etc…. customfield sku, customfield priceI read in and parse the tab-delimited file and two situations occur.
1. if the record contains an ID then the script will update the current WordPress posting with the new info. (this part works).
2. If the record does NOT contain an ID, then the script creates a new post, and populates the wordpress fields in the dbase. — the problem here is I cannot figure out how to populate the custom fields with this method.any help please?
The line of interest is how to add
add_post_meta($my_post[‘ID’] , ‘sku’, $sku); to the CREATE post option, as I DO NOT KNOW HOW TO GET THE POST ID I’ve just created to enable the add_post_meta function to work.
Although I include
$my_post[‘price’] = $price;
$my_post[‘sku’] = $sku; in the args for the NEW POST… it does not seem to insert these upon post creation. NO problem at all when UPDATING a post, though.here is the code specifics of the function I use so far.
function updateGS() {
$filename = $_SERVER[“DOCUMENT_ROOT”] . ‘/navs/WP_update_GS.txt’;
if ($fileContents = file_get_contents($filename)) {
$contentsArray = explode(“\r”, $fileContents) ;
$numlines = count($contentsArray)-1;
$i=0;
flush();
while ($i <= $numlines) {
$thisItem = ”;
$thisItem = $contentsArray[$i];
$atribs= explode(“\t”, $thisItem);
$thetags = explode(“,” , $atribs[4] );
$thetagslist = $thetags[0];
if ($thetags[1] !=”) $thetagslist .= ‘,’ . $thetags[1] ;
if ($thetags[2] != ”) $thetagslist .= ‘,’ . $thetags[2] ;
$price = $atribs[5] ;
$sku= $atribs[6] ;$my_post = array();
$my_post[‘ID’] = $atribs[0] ;
$my_post[‘post_type’] = ‘post’;
$my_post[‘post_title’] = $atribs[1] ;
$my_post[‘post_content’] = $atribs[2] ;
$my_post[‘post_status’] = ‘publish’;
$my_post[‘post_author’] = ‘1’;
$my_post[‘post_category’] = array($atribs[3]);
$my_post[‘tags_input’] = $thetagslist ;
$my_post[‘price’] = $price;
$my_post[‘sku’] = $sku;// Update the post into the database
if ($my_post[‘ID’] >1) {
wp_update_post( $my_post );if (!update_post_meta($my_post[‘ID’] , ‘sku’, $sku)) add_post_meta($my_post[‘ID’] , ‘sku’, $sku);
if (!update_post_meta($my_post[‘ID’] , ‘price’, $price)) add_post_meta($my_post[‘ID’] , ‘price’, $price);} else {
wp_insert_post( $my_post ); }
$i++ ;
} } }
- The topic ‘how to add post_meta data to a newly created post – by csv import?’ is closed to new replies.