3

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: Image thumbnails with links

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(&quot;{$att->ID}&quot;, &quot;{$nonce}&quot;);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!

1 Answer 1

3

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:

    set_post_thumbnail( $post, $thumbnail_id );
//or
    update_post_meta( $post->ID, '_thumbnail_id', $attachment_id );

and to unset use

delete_post_meta( $post_ID, '_thumbnail_id' );
1
  • Thanks, using update_post_meta has worked perfectly via an AJAX call :) I was able to hook into AJAX methods already working within the metabox script I was using and managed to make it work fairly easily. Mar 9, 2011 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.