• Resolved infmgt

    (@infmgt)


    According to the Codex, when using wp_insert_post a page is created or updated depending upon the contents of $post_id. If this is zero, a new page is created. Otherwise, the post with the id which is set in $post_id will be updated.

    I have a routine which creates a page using wp_insert_post. The routine works. However, if I try to update an already created new page, a second page is created rather than the old one being modified – even though the routine has a mechanism to avoid this:

    $list_name = $_REQUEST["list_name"];
    
    // Set (or get) the page id so as to create or update	
    $page_id = 0;	
    global $wpdb; // Code is within a function
    	
    $sql = $wpdb->prepare( "SELECT ID, post_title FROM wp_mgf_posts WHERE post_title = %s ORDER BY ID DESC LIMIT 1",$list_name);
    $results = $wpdb->get_results( $sql,ARRAY_A);
    	
    var_dump($results); 	
    	
    foreach($results as $result)
    {
    $page_id = $result['ID'];	
    }
    	
    echo 'Page id = ' . $page_id;
    	
    // Create (or update) the page	
    $plant_list = array(
      'post_ID'      => $page_id,     // 0 for create, existing page id for update
      'post_title'    => $list_name,  // the title of the list
      'post_content'  => $content,   // page content
      'post_status'   => 'publish',
      'post_author'   => 1,
      'post_type'   => 'page',
      'post_category' => array(26,30)  // development and plant list categories
    );
    $insert = wp_insert_post( $plant_list );

    As you can see, I have put in a var_dump and an echo of the retrieved post_id. This is the result:

    array(1) {
    [0]=>
    array(2) {
    [“ID”]=>
    string(4) “7001”
    [“post_title”]=>
    string(18) “Late Summer Colour”
    }
    }
    Page id = 7001

    This looks OK to me. Presumably, I’m doing something wrong but have no idea what. Can anyone help?

Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Problem with wp_insert_post’ is closed to new replies.