WordPress.org

Ready to get started?Download WordPress

Forums

Need help with insert_post and custom fields (3 posts)

  1. harry1961
    Member
    Posted 3 years ago #

    I am using the following piece of code to bulk import data from a mysql database into the wp database

    require("setup.php");
    $conn =	mysql_connect($dbhost,$dbuser,$dbpasswd);
    mysql_select_db($dbname,$conn);
    
    $results = mysql_query("SELECT * FROM data LIMIT 10",$conn);
    
    $i = 0;
    while ($row = mysql_fetch_array($results,MYSQL_ASSOC)) {
    
    $ID = $row['adid'];
    $Title = stripslashes($row['adtitle']);
    $Title = utf8_encode($Title);
    
      $post = array();
      $post['post_status'] = 'publish';
      $post['post_category'] = array(5,6);
      $post['post_title'] = $Title;
      $post['post_content'] = $row['subcatname'];
      $post['tags_input'] = $Tags;
      $posts[$i] = $post;
      $i++;
    }
    
    mysql_free_result($results);
    mysql_close($conn);
    
    require('../wp-load.php');
    
    foreach ($posts as $post) {
      wp_insert_post($post);
    echo $Tags;
    }

    Everything works fine so far but i need to import some custom fields also and i dont know how to add them into this code. Anybody can help ?

  2. aut0poietic
    Member
    Posted 3 years ago #

    If you're wanting to add additional fields to a post you can use add_post_meta() (http://codex.wordpress.org/Function_Reference/add_post_meta).

    It looks like it is a part of wp-includes/post.php so you should have access to the method if you have access to wp_insert_post.

    Hope that hit what you were looking for.

  3. harry1961
    Member
    Posted 3 years ago #

    Thank you, that points me in the right direction. Now i modified the last part:

    require('../wp-load.php');
    foreach ($posts as $post) {
    $published_id = wp_insert_post($post);
    add_post_meta($published_id, "cp_extern", $Title);

    and it imported one custom field of the last post. But where do i have to put the code so that it imports the custom fields of all 10 posts ?

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.