WordPress.org

Ready to get started?Download WordPress

Forums

Issue with post_name and wp_insert_post when updating (3 posts)

  1. polsola
    Member
    Posted 1 year ago #

    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(
    							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
    			$insertHouse++;
    		}
    		else {
    			$updateHouse++;
    			// 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 );
  2. x500.net
    Member
    Posted 1 year ago #

    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.

  3. polsola
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic