WordPress at Your Fingertips

Change GUID field on create / update post

It's convenient in some cases to set real working post URL to the guid field. For example if we have difficult logic of post URL creation, it's better to save it to guid field and just take it when we need the URL.

Example code of how to save post URL to the GUID wp_posts table field.

# Change GUID field on create / update post
# in admin (the permalink writes in current structure)
add_action( 'save_post', 'permalink_to_post_guid' );

function permalink_to_post_guid( $post_id ){
	global $wpdb;

	$guid = get_permalink( $post_id );
	$wpdb->update( $wpdb->posts, [ 'guid' => wp_make_link_relative( $guid ) ], [ 'ID'=>$post_id ] );

	clean_post_cache( $post_id );
}

The same, but for specified post_type only:

# Change GUID field on create / update post
# in admin (the permalink writes in current structure)
add_action( 'save_post_posttype', 'permalink_to_post_guid' );

function permalink_to_post_guid( $post_id ){
	global $wpdb;

	$guid = get_permalink( $post_id );
	$wpdb->update( $wpdb->posts, [ 'guid' => wp_make_link_relative( $guid ) ], [ 'ID'=>$post_id ] );

	clean_post_cache( $post_id );
}
No comments
    Log In