Support » Fixing WordPress » Issue with post_name and wp_insert_post when updating

  • Hello!

    I’m creating a system to import some data from a Json to a WordPress custom post type posts.

    I successfully done this when inserting new data, but when it’s time to update (I check if the post exists by a custom post meta) the post_name or slug either is gone or adds me the -2 or -3 after the name.

    I think that is some issue with WordPress checking if the post_name exists, but I don’t know if there is a way to disable this check.

    My code goes like this:

    // Check if id exists, in that case update house
    		$pages = get_posts(
    				array(	'post_type' => 'house',
    						'meta_query' => array(
    								'key' => 'house_id',
    								'value' => $id_house,
    		//Prepare Array with values
    		$my_house = array(
    		  'post_title'    => $house['name'],
    		  'post_name'	  => sanitize_title_with_dashes($house['name'],'','save'),
    		  'post_type'     => 'house',
    		  'post_status'   => 'publish',
    		  'post_content'  => $house['propietaryComment']
    		if(count($pages) == 0) {
    			// House doesn't exist, create new one
    		else {
    			// House exist, get the ID
    			foreach ( $pages as $page ) {
    				$my_house = array('ID'=> $page->ID)+$my_house;
    		// Insert/Update house into the database
    		$house_post_id = wp_insert_post( $my_house );
Viewing 2 replies - 1 through 2 (of 2 total)
  • In WP, each post must have its own unique slug. When you try to add a new house with a name same as the existing one, the WP checks if the slug exists and appends a number if the matching slug was found in the DB, hence you see the -2, -3 added.
    You should prevent this functionality. Use wp_update_post for updating the post by slug and not inserting a new one.

    I will give a try to wp_update_post, thanks for the reply!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Issue with post_name and wp_insert_post when updating’ is closed to new replies.