For a custom plugin I’m working on, I have added a checkbox element to the attachments editor in a manner like the answer provided here:
How to add a checkbox element to attachments editor with example
What I would like to do is, based on the value of that checkbox, alter the behavior of the “Insert into Post” button. Eg., if the checkbox is not checked, “Insert into Post” does the default WordPress action for the file type. If the box is checked, insert my plugin shortcode instead. I’ve tried the following (based on the answer here):
function my_media_insert($html, $id, $caption, $title, $align, $url, $size, $alt) {
$orig_html = $html;
$attachment = get_post($id);
$my_meta = get_post_meta($post->ID, '_myMeta', true); // try to get checkbox value
$mime_type = $attachment->post_mime_type;
if (($mime_type == "application/pdf") && ($my_meta == "1")) {
$src = wp_get_attachment_url( $id );
$html = '[shortcode url="'.$src.'"]';
} else {
$html = $orig_html;
}
return $html;
}
add_filter('media_send_to_editor', 'my_media_insert', 20, 3);
…but get_post_meta() never seems to return any value to work with. (If I change the value of $html to $my_meta for testing purposes, the insertion is “blank”.)
The short version: Is there a way for me to set metadata on an attachment with a checkbox, and alter the value of $html sent to the editor in response?
UPDATE: I found an example that accomplishes basically what I want to do (changes the behavior of the button) but I would like to adapt this to add a checkbox on the attachment metadata that would do this versus doing this for every file all the time. That way the behavior can be overridden when needed and I can apply it only to specific file types.
http://justingable.com/2008/10/03/modifying-wordpress-default-method-for-inserting-media/
In case it’s helpful to anyone else, here’s what my code looked like to achieve this. I didn’t end up saving the attachment data at all, per tbuteler’s suggestion, but rather than using $_REQUEST I found I could use the $attachment array directly:
EDIT 1/2013: This solution no longer works in WordPress 3.5+. The box-checking on the attachment screen sends an AJAX request to save the attachment metadata. There doesn’t seem to be a way to use a checkbox merely as a “flag” on the attachment screen anymore in light of this. If someone finds another solution, I will happily change the approved answer!