在WordPress中以程序方式一次删除一个文件



我正在我的自定义主题中构建一个WordPress自定义文件上传器,现在我需要能够在点击按钮时删除每个文件。到目前为止,我有这个:

<?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 } ?>


}

发生的情况是,当按下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_delete_attachment( $_GET['id'] )

相关内容

最新更新