network-media-library icon indicating copy to clipboard operation
network-media-library copied to clipboard

Save the featured image via REST API if the media post ID doesn't exist in the non-media site

Open stuajnht opened this issue 5 years ago • 2 comments

Description

When using the Gutenberg editor to add a featured image, if the value of the post ID of the image on the media site doesn't exist in the non-media site that the featured image is being applied to, the featured image is not saved correctly.

This commit hooks into the rest_insert_ action and saves the post ID of the featured image to the post meta table of the non-media site.

Related Issue

#49

stuajnht avatar Mar 04 '19 01:03 stuajnht

@stuajnht I have a small problem with this. It works great when there are no metaboxes (Yoast SEO for example). With metaboxes it looks like first the thumbnail_id is saved but it's overwritten by the the metabox save.

For now I have added a small workaround:

if ( array_key_exists( 'featured_media', $request_json ) ) {
	update_post_meta( $post->ID, '_thumbnail_id', $request_json[ 'featured_media' ] ); //so the preview works correctly
	update_post_meta( $post->ID, '_image_to_save', $request_json[ 'featured_media' ] );
}

and I add:

add_action( 'load-post.php', 'post_listing_page' );
function post_listing_page() {
	if( isset( $_GET['post'] ) && intval($_GET['post']) ) {
		$img = get_post_meta( $_GET['post'], '_image_to_save', true );

		if( $img != '' ) {
			update_post_meta( $_GET['post'], '_thumbnail_id', $img );
		}
	}
}

So I replace the img with the temporary one. Yet I know this is just a workaround. Do you have a better idea how to fix this.

palmiak avatar Jul 11 '19 09:07 palmiak

👋 Hey all, any movement on this? We are using the code in this PR with Gutenberg but would love to see a merge / release.

davidegreenwald avatar Feb 10 '23 21:02 davidegreenwald