在我的WP 4.4 216th子主题中,我想从插件创建的前端表单中删除帖子图像附件。为了实现这一点,我遵循this answer, 但是删除链接不会删除任何内容(它们将我链接到页面顶部)。这里怎么了?
UPDATE [已解决]
With the commenters help and after fixing some errors I solved my problem. Thank you! Below is the fixed code.
在插件创建的前端表单中,我获取帖子ID并显示其图像附件以及删除链接:<!-- Display item thumbnails -->
<?php if( \'POST\' == $_SERVER[\'REQUEST_METHOD\'] && isset( $_POST[\'postid\'] ) ) {
$images = get_children( array ( \'post_parent\' => $_POST[\'postid\'], \'post_type\' => \'attachment\', \'post_mime_type\' => \'image\' ));
if ( empty( $images ) ) {
// no attachments here
} else {
echo \'<label for="item_thumbnails">Post thumbnails</label>\';
echo \'<div class="item_thumbnails">\';
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, \'thumbnail\' ) . \'<br>\'; ?>
<!-- add a \'Delete\' link -->
<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\' ); ?>" />
<?php }
echo \'</div>\';
}
}?>
在插件的“js”子目录中,我创建了一个名为“delete_attachment”的jQuery脚本。js’:// this is for jQuery 1.7+
//jQuery(\'.remImage\').on(\'click\', function(event) {
// this is for jQuery 1.4.3+
jQuery(document).delegate(\'.remImage\', \'click\', function(event) {
// this is for jQuery 1.3+ (deprecated)
//jQuery(\'.remImage\').live(\'click\', function(event) {
event.preventDefault();
var attID = jQuery(this).attr(\'name\');
jQuery.ajax({
type: \'post\',
url: MyAjax.ajaxurl,
data: {
action: \'delete_attachment\',
attID: jQuery(this).attr(\'name\'),
_ajax_nonce: jQuery(\'#nonce\').val(),
post_type: \'attachment\'
},
success: function() {
console.log(\'#file-\'+attID)
jQuery(\'#file-\'+attID).fadeOut();
}
});
})
我将其放入插件文件中:function the_plugin_scripts() {
wp_enqueue_script( \'delete-attachment\', plugins_url( \'js/delete_attachment.js\' , __FILE__ ), array(\'jquery\') );
wp_localize_script( \'delete-attachment\', \'MyAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'the_plugin_scripts\' );
在同一个插件文件中,我添加了一个处理AJAX请求的函数:add_action( \'wp_ajax_delete_attachment\', \'delete_attachment\' );
function delete_attachment( $post ) {
//echo $_POST[\'attID\'];
$msg = \'Attachment ID [\' . $_POST[\'attID\'] . \'] has been deleted!\';
if( wp_delete_attachment( $_POST[\'attID\'], true )) {
echo $msg;
}
die();
}