Support

Account

Home Forums General Issues Using custom fields (including post relationship) to build custom post title

Solving

Using custom fields (including post relationship) to build custom post title

  • Hey guys, I’m trying to build a custom post title using ACF custom fields. I’m almost there. Code below.

    The one area that’s holding me up is I’m grabbing the $location variable from a relationship field (location_relationship) to include in the slug string.

    It should look like: /location-start-date-end-date. However, it’s returning /start-date-end-date on “Publish”. On “Update” it then adds /location- to the slug string.

    Any ideas on what I should look into to get the location into the slug upon post publish?

    Thank so much!

    Josh

    
    // Auto-populate post title with Event dates.
    function loud_update_postdata( $value, $post_id, $field ) {
    	
    	$date_start = strtotime(get_field('trip_departure_date', $post_id));
    	$date_end = strtotime(get_field('date', $post_id));
    	$location_relationship = get_field('location_relationship', $post_id);
    
    	$location = $location_relationship[0]->post_title;
    
    	if( $date_start == $date_end ) {
    		
    	     $start = date_i18n('M d Y', $date_start);
    	     $title = $start;
    		
    	} else {
    		
    	     $start = date_i18n('M d Y', $date_start);
    	     $end = date_i18n('M d Y', $date_end);
    	     $title = $location .' - '. $start .' - '. $end;
    	}
    
    	$slug = sanitize_title( $title );
    
    	$postdata = array(
    	     'ID'	   => $post_id,
        	 'post_title'  => $title,
    	     'post_type'   => 'short_term_trips',
    	     'post_name'   => $slug
      	);
      
    	wp_update_post( $postdata );
    	
    	return $value;
    	
    }
    add_filter('acf/update_value/name=trip_departure_date', 'loud_update_postdata', 10, 3);
    add_filter('acf/update_value/name=date', 'loud_update_postdata', 10, 3);
    add_filter('acf/update_value/name=location_relationship', 'loud_update_postdata', 10, 3);
    
  • Hi @joshdoxicology-com

    Your code looks fine and should work.

    Have you tried to debug the data contained in the $location, $start and $end variables. This can give you insights into what could be causing the issue.

    For more info, check out: http://www.advancedcustomfields.com/resources/debug/#debugging-data

  • Thanks, James, for the response.

    This is not my strong suit, but…

    Do you think the issue lies with the fact that the third filter is running before a post ID has been created? That it can only update the postdata if the post has been created?

    Could it be because this is running from a Relationship custom field, and it can only reference $post_id upon “Update” and NOT “Publish”?

    Thanks again!

    J

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Using custom fields (including post relationship) to build custom post title’ is closed to new replies.