I currently have a custom post type in a theme I’m developing which will be used for portfolio items. So far, I have implemented functionality that allows images to be attached to a portfolio post.
I now need the best way to go about detaching images from a post: My code currently is:
$images =& get_children('post_type=attachment&post_mime_type=image&post_parent=$post->ID');
$numberOfImages = count($images);
if($numberOfImages == 1) {
}
else if($numberOfImages > 1)
{
foreach($images as $attachment_id => $attachment)
{
$imageAttributes = wp_get_attachment_image_src($attachment_id);
?>
<div class="element">
<img alt="" height="100" src="<?php echo $imageAttributes[0]; ?>" width="150" />
<a href="#" title="Unattach this media item.">Unattach</a>
</div>
<?php
}
}
This loops through the images that are attached and displays them in a meta box with an associated ‘Unattach’ button. I am at a loss as to what/where I need to link to to detach the images from the post. Any help appreciated.
This can be done using an Ajax call that will query the database and set the parent as “zero”.
First, create a meta box, enqueue the Javascript that calls the
unattach
function and register this WP_Ajax function.This is the enqueued Javascript file (
script.js
). It makes the Ajax call that will execute a MySql query to unattach and removes the thumbnail from the meta box.Result: