• Okey. So I used to have a problem with looping when I tried to change information of a post while I was publishing it.

    This is my example: I wanted to post a last.fm event and the only thing you needed was to write an url in the title field and the rest of the information would be filled out.

    <?php
    
    function lastfmshows_save_show($post_id){
    
    	if(!wp_is_post_revision($post_id)){
    		global $wpdb;
    		$my_post = get_post($post_id);  
    
    		//I want to save the url in another field
    		$url = $my_post->post_title;
    		$split_url = explode('/' ,$url);
    		$split_event = explode('+', $split_url[4]);
    
    		//Get the data
    		$fullapi = 'https://ws.audioscrobbler.com/2.0/?method=event.getinfo&format=json&event='.$split_event[0].'&api_key='. LASTFM_API;
    		$xml = json_decode(file_get_contents($fullapi));
    
    		//Only add meta if city doesn't exist
    		if(get_post_meta($post_id, 'city', true)){
    			return;
    		}else{
    			$date = DateTime::createFromFormat('D, j M Y H:i:s',$xml->event->startDate);
    			add_post_meta($post_id, 'city', $xml->event->venue->location->city);
    			add_post_meta($post_id, 'venue', $xml->event->venue->name);
    			add_post_meta($post_id, 'url', $url);
    			add_post_meta($post_id, 'id', $xml->event->id);
    			add_post_meta($post_id, 'date', $date->format('ymd'));
    		}
    		$postdata = array(
    			'ID' => $post_id,
    			'post_title' => $xml->event->title,
    			'post_status' => 'publish',
    			'post_name' => sanitize_title($xml->event->title)
    		);
    
    		wp_update_post($postdata);
    
    	}
    
    }
    
    add_action('publish_event', 'lastfmshows_save_show');
    
    ?>

    At first I thought this would just create a loop since post status is “publish” and I the action trigger was on publish_event (event is my custom post type).

    The thing I noticed that wasn’t working as I’m used to was add_post_meta after wp_update_post. It needs to be before. I have no idea why.

    So what does this code do exactly?

    1. I write an last.fm event url. Save the title to a variable so it can be used in a custom field called url.

    2. I add the fields I need so they can be filled with data from last.fm.

    3. Then I change the title to the new one, which is the title of the actual event from last.fm. I am also changing the permalink (post_name) to a new one matching the title.

    Any thoughts? ??

  • The topic ‘How to: Change post content while publishing’ is closed to new replies.