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

获取自定义文章类型PostId异常,无法将已发布文章转为草稿

问题解决:自定义文章类型无法通过URL获取PostID并更新状态

核心问题分析

你的代码主要存在两个问题:

  • url_to_postid 默认对自定义文章类型的URL支持有限,WordPress的重写规则可能没正确匹配到自定义文章类型的链接,导致返回0或空值。
  • 条件判断的逻辑括号位置错误,导致有效PostID的判断失效。

解决方案

1. 修正条件判断逻辑

原代码中!is_null(get_post($postId) && is_numeric($postId))的括号逻辑错误,正确判断应该先验证ID为数字,再检查文章是否存在:

if(is_numeric($postId) && $postId > 0 && !is_null(get_post($postId))) {

2. 替换url_to_postid为自定义文章类型适配的ID获取方式

url_to_postid依赖全局重写规则,对自定义文章类型兼容性差,推荐用get_page_by_path直接根据路径匹配,同时指定目标文章类型:

// 解析URL提取相对路径
$url_parts = parse_url($full_url);
$relative_path = ltrim($url_parts['path'], '/');

// 替换成你的自定义文章类型slug,比如'product'、'portfolio'
$post = get_page_by_path($relative_path, OBJECT, 'your_custom_post_type');
$postId = $post ? $post->ID : 0;

3. 完整修正后的代码

foreach ($file_data as $link){
    // 拼接完整URL,统一处理协议
    $full_url = '';
    if ($_SERVER['HTTP_HOST'] == 'localhost'){
        $full_url = "http://" . $_SERVER['HTTP_HOST'] . $link;
    }else{
        $full_url = "https://" . $_SERVER['HTTP_HOST'] . $link;
    }
    
    // 解析URL获取相对路径
    $url_parts = parse_url($full_url);
    $relative_path = ltrim($url_parts['path'], '/');
    
    // 替换为你的自定义文章类型slug
    $custom_post_type = 'your_custom_post_type';
    $post = get_page_by_path($relative_path, OBJECT, $custom_post_type);
    $postId = $post ? $post->ID : 0;

    if(is_numeric($postId) && $postId > 0 && !is_null(get_post($postId))) {
        $status = get_post_status($postId);
        if($status == 'publish'){
            wp_update_post(array(
                'ID'          => $postId,
                'post_status' => 'draft'
            ));
        }
    }
}

额外注意事项

  • 确保自定义文章类型注册时设置了public => true和rewrite => array('slug' => 'your-slug'),并且已刷新WordPress固定链接设置(进入「设置→固定链接」页面保存一次即可)。
  • 如果自定义文章类型有层级结构,get_page_by_path需要传入完整的层级路径才能正确匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:44:48