I am implementing a custom Meta box that allows the user to add images via a simple file input field (based around code on this site: Meta Box Script). This code allows multiple images to be added as attachments to the page and it does it without the full upload dialogue box, you just select the image file and publish the page and the image is uploaded. This works great, however, I would like to be able to add a link on each image so that you can set an image as a featured image.
Here’s an image showing what this looks like:
I snooped around the standard image uploader and can see that there is a JS file (/wp-admin/js/set-post-thumbnail.js) that is triggered as an AJAX call and this sets the image as a featured image. I’m using the following code (echo’d by PHP hence the escaping) to add the ‘Use as featured image’ link:
<script type="text/javascript" src="/wp-admin/js/set-post-thumbnail.js"></script>
<a class="wp-post-thumbnail" id="wp-post-thumbnail-1915" href="javascript:void(0)" onclick="WPSetAsThumbnail("{$att->ID}", "{$nonce}");return false;">Use as featured image</a>
I figured this much out with a bit of trial and error but it doesn’t work as I get an error Uncaught ReferenceError: setPostThumbnailL10n is not defined
, this is because I don’t have JS loaded that provides the setPostThumbnailL10n
and probably other problems too!
Basically I’m trying to figure out if it’s feasible to tap into this inbuilt functionality easily. My other option is to roll my own JS which saves an image as featured instead. I will also require being able to unset an images as featured too. Any ideas greatly welcome as this seems kind of uncharted territory as Googling this hasn’t come up with anything!
even if you had included the all of the needed files you will still have to create your some extra hidden fields like _nonce to pass the
check_ajax_referer( "set_post_thumbnail-$post_ID" );
also you would need to create an action hidden field to identify the case of Ajax call with the value :
"set-post-thumbnail"
You are better of creating your own Ajax call
and simply use in your callback function:
and to unset use