Php 在WordPress中以编程方式一次删除一个文件
我正在自定义主题中构建WordPress自定义文件上传程序,现在我需要能够在单击按钮时删除每个文件。 到目前为止,我有:Php 在WordPress中以编程方式一次删除一个文件,php,wordpress,Php,Wordpress,我正在自定义主题中构建WordPress自定义文件上传程序,现在我需要能够在单击按钮时删除每个文件。 到目前为止,我有: <?php $attachments = get_posts( array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' =&g
<?php
$attachments = get_posts(
array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
)
);
foreach ( $attachments as $attachment ) {
$file_link = wp_get_attachment_url($attachment->ID, "full");
$file_img = wp_get_attachment_image($attachment->ID);
$file_title = get_the_title($attachment->ID);
$size_media = filesize(get_attached_file($attachment->ID));
$total_size = ($size_media) / 1000;
?>
<div>
<a href="http:<?php echo $file_link; ?>" target="_blank">
<div>
<?php if (strpos($file_link, '.png') !== false || strpos($file_link, '.jpg') !== false || strpos($file_link, '.gif') !== false || strpos($file_link, '.tif') !== false ) {
echo '<span class="material-icons">insert_photo</span>';
} else {
echo '<span class="material-icons">description</span>';
}
?>
</div>
</a>
</div>
<div>
<a href="http:<?php echo wp_get_attachment_url($attachment->ID, "full"); ?>" target="_blank">
<p><?php echo $file_title; ?></p>
</a>
<p>Size: <?php echo $total_size; ?>KB</p>
<a href="<?php wp_delete_attachment( $attachment->ID ); ?>">Delete</a>
</div>
<?php } ?>
}
大小:KB
}
当按下Delete链接时,所有文件都被删除。我不想那样。我只需要一个文件,其中的链接被按下删除。您对html中包含的php函数的假设是错误的。php所做的是输出一些html。在您的情况下,您正在做的是:
<a href="<?php wp_delete_attachment( $attachment->ID ); ?>">Delete</a>
这会告诉Wordpress立即删除附件。然后它将不返回任何内容,因此您的html将如下所示:
<a href="">Delete</a>
您需要的是一个javascript函数,该函数执行ajax请求,通知服务器端php删除特定附件。您可以在html中调用此选项:
<a href="deleteFile(<?php echo $attachment->ID ?>);">Delete</a>
这将产生以下html:
<a onclick="deleteFile(30);">Delete</a>
删除
现在您可以编写一个名为deleteFile
的javascript函数,并将附件id作为参数。它应该将id发送到服务器并调用wp\u delete\u attachment($\u GET['id'])