I currently have a gravity form which submits images to the gallery of a specific post. What I am looking to add is the option to display the thumbnails of each image attached to that specific post, with a button that will remove the image from the gallery.
[[LINK href="http://codex.wordpress.org/Function_Reference/wp_get_attachment_image"]]This page[[/LINK]] has the function for returning the images of the current page, so that part is somewhat covered, I just need it applied to post 2.
It is the delete button that makes this more difficult. So foreach li in that function there needs to be an onclick event, that will remove the attachment by id.
So the boiled down final output is something along the lines of...
if exists post 2
get attachments for post 2
<ul>
foreach $attachments as $attachment
<li>
echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
echo 'input onclick=delete $attachment';
</li>
</ul>
Arnav Joy answers:
try this
<ul>
<?php foreach ($attachments as $attachment ) { ?>
<li>
<?php echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );?>
<a class="remImage" name="<?php echo $attachment->ID; ?>" href="#"><?php _e('delete');?></a> <input type="hidden" id="att_remove" name="att_remove[]" value="<?php echo $attachment->ID; ?>" />
<input type="hidden" name="nonce" id="nonce" value="<?php echo wp_create_nonce( 'delete_attachment' ); ?>" />
</li>
<?php } ?>
</ul>
<script>
jQuery(document).ready(function($){
$('.remImage').live('click', function() {
var attID = jQuery(this).attr('name');
jQuery.ajax({
type: 'post',
url: '<?php echo get_bloginfo('url');?>/wp-admin/admin-ajax.php',
data: {
action: 'delete_attachment',
att_ID: jQuery(this).attr('name'),
_ajax_nonce: jQuery('#nonce').val(),
post_type: 'attachment'
},
success: function() {
console.log('#file-'+attID)
$('#file-'+attID).fadeOut();
}
});
});
</script>
in functions.php
<?php
add_action( 'wp_ajax_delete_attachment', 'delete_attachment' );
function delete_attachment( $post ) {
//echo $_POST['att_ID'];
$msg = 'Attachment ID [' . $_POST['att_ID'] . '] has been deleted!';
if( wp_delete_attachment( $_POST['att_ID'], true )) {
echo $msg;
}
die();
}
?>
or see this article
http://marketplace.tutsplus.com/forums/thread/wordpress-javascript-php-problem/60982?page=1
Kyle comments:
Thanks for the reply, so I can get this right the first time-where in this would I define the post ID
Arnav Joy comments:
add following at the very begning
<?php
$postID = 2 // change here for your post id
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $postID,
) );
?>
Kyle comments:
As in I think you are missing this part:
if exists post 2
get attachments for post 2
Arnav Joy comments:
yes add this at the very begning of my code which i gave you
<?php
$postID = 2 // change here for your post id
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $postID
) );
?>