wp_ajax_set_post_thumbnail() WordPress Function

The wp_ajax_set_post_thumbnail() function allows you to set the post thumbnail for a post via an AJAX call. This function is useful for setting the post thumbnail when you are editing a post and need to change the thumbnail without reloading the page.

wp_ajax_set_post_thumbnail() #

Ajax handler for setting the featured image.


Source

File: wp-admin/includes/ajax-actions.php

function wp_ajax_set_post_thumbnail() {
	$json = ! empty( $_REQUEST['json'] ); // New-style request.

	$post_ID = (int) $_POST['post_id'];
	if ( ! current_user_can( 'edit_post', $post_ID ) ) {
		wp_die( -1 );
	}

	$thumbnail_id = (int) $_POST['thumbnail_id'];

	if ( $json ) {
		check_ajax_referer( "update-post_$post_ID" );
	} else {
		check_ajax_referer( "set_post_thumbnail-$post_ID" );
	}

	if ( '-1' == $thumbnail_id ) {
		if ( delete_post_thumbnail( $post_ID ) ) {
			$return = _wp_post_thumbnail_html( null, $post_ID );
			$json ? wp_send_json_success( $return ) : wp_die( $return );
		} else {
			wp_die( 0 );
		}
	}

	if ( set_post_thumbnail( $post_ID, $thumbnail_id ) ) {
		$return = _wp_post_thumbnail_html( $thumbnail_id, $post_ID );
		$json ? wp_send_json_success( $return ) : wp_die( $return );
	}

	wp_die( 0 );
}


Top ↑

Changelog

Changelog
VersionDescription
3.1.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More