删除WordPress文章时同步删除自定义字段中的媒体ID对应媒体文件
实现删除文章时同步删除关联媒体文件的代码示例
以下分两种常见平台场景提供代码片段,你可根据实际使用环境选择:
WordPress 场景
借助WordPress的文章删除钩子,在文章删除前读取自定义字段中的媒体ID数组,逐一清理对应媒体文件:
// 绑定文章删除前的钩子 add_action('before_delete_post', 'delete_associated_media_on_post_delete', 10, 1); function delete_associated_media_on_post_delete($post_id) { // 替换为你存储媒体ID数组的自定义字段键名 $media_ids = get_post_meta($post_id, 'your_meta_key', true); // 验证媒体ID数组有效性 if (!empty($media_ids) && is_array($media_ids)) { foreach ($media_ids as $media_id) { // 检查是否为有效附件(可按需调整媒体类型判断) if (wp_attachment_is_image($media_id) || wp_attachment_is('audio', $media_id) || wp_attachment_is('video', $media_id)) { // true参数表示同时删除服务器文件,false仅删除数据库记录 wp_delete_attachment($media_id, true); } } } }
关键提示
- 必须替换
your_meta_key为实际使用的自定义字段键名 wp_delete_attachment的第二个参数控制是否删除服务器物理文件,按需调整- 建议先在测试环境验证逻辑,避免误删重要文件
Shopify 场景
通过监听Shopify的delete_article webhook,获取文章的metafield数据后调用API删除关联媒体:
const express = require('express'); const router = express.Router(); const Shopify = require('shopify-api-node'); // 初始化Shopify API客户端 const shopify = new Shopify({ shopName: 'your-shop-name.myshopify.com', apiKey: 'your-api-key', password: 'your-api-admin-password', }); // 处理文章删除webhook router.post('/webhooks/article-deleted', async (req, res) => { const articleId = req.body.id; try { // 获取目标metafield(替换为你的命名空间和字段键) const targetMetafield = await shopify.metafield.list({ owner_resource: 'article', owner_id: articleId, namespace: 'custom', key: 'associated_media_ids' }); if (targetMetafield.length > 0) { const mediaIds = JSON.parse(targetMetafield[0].value); // 循环删除媒体文件(这里以Shopify File为例,若为主题资产请改用asset接口) for (const mediaId of mediaIds) { await shopify.file.delete(mediaId); } } res.sendStatus(200); } catch (err) { console.error('删除关联媒体失败:', err); res.sendStatus(500); } }); module.exports = router;
关键提示
- 需在Shopify后台配置
delete_article类型的webhook,指向上述接口地址 - 替换所有占位符(店铺名、API密钥、metafield命名空间等)为实际信息
- 若关联的是主题资产,需将
shopify.file.delete改为shopify.asset.delete并调整对应参数
内容的提问来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

