You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:删除关联CCT内容的WordPress自定义函数失效问题

修复删除CPT时同步删除关联CCT条目的代码

原代码存在的问题

  • 核心逻辑偏差:错误使用文章slug(还处理了__trashed后缀)匹配post_id字段,但需求是匹配被删除CPT的ID,完全偏离目标
  • 冗余代码:post_type数组重复设置chat
  • 缺少类型校验:未判断当前被删除的是否为目标CPT,可能误删其他文章关联的chat条目

修正后的代码

add_action('before_delete_post', 'delete_associated_chat_entries');
function delete_associated_chat_entries($postId) {
    // 获取当前被删除的文章对象
    $post = get_post($postId);
    if (!$post) return;

    // 替换为你的目标CPT类型(比如你的CPT叫"custom_post")
    $target_cpt = 'custom_post';
    if ($post->post_type !== $target_cpt) return;

    // 查询所有post_id字段等于当前CPT ID的chat条目
    $query = new WP_Query([
        'post_type' => 'chat',
        'meta_query' => [
            [
                'key' => 'post_id',
                'value' => $postId,
                'type' => 'numeric', // 确保数字类型匹配准确
                'compare' => '='
            ]
        ],
        'posts_per_page' => -1, // 获取所有匹配条目
        'no_found_rows' => true, // 关闭分页计数提升性能
        'fields' => 'ids' // 仅返回ID,减少内存占用
    ]);

    // 循环删除匹配的chat条目
    foreach ($query->posts as $chat_id) {
        wp_delete_post($chat_id, true); // true表示强制删除,不进入回收站
    }
}

关键修改说明

  1. 直接使用$postId匹配post_id字段,完全贴合需求逻辑
  2. 增加CPT类型校验,仅在删除指定CPT时执行删除操作,避免误删
  3. 优化WP_Query参数,提升查询性能并减少资源占用
  4. 移除冗余代码,让逻辑更清晰

内容的提问来源于stack exchange,提问作者Fabio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:52:44