WordPress插件transition_post_status钩子下$post->ID为空无法获取特色图URL
问题原因梳理
- 无需额外声明全局
$post:transition_post_status钩子的第三个参数已经默认传入触发状态变更的文章对象,你额外声明的全局$post可能被其他插件/主题代码污染,导致和钩子传入的有效文章对象不一致,建议直接删除全局$post的声明。 - $post->ID为空的核心诱因:发布文章时WordPress会同步生成修订版本(revision)、自动草稿等特殊类型的临时文章数据,这类对象没有关联特色图,部分场景下ID会为空。你的代码没有对这类特殊内容做过滤,就会偶发拿不到ID、获取特色图失败的问题。
- 作者信息获取逻辑错误:
get_the_author_meta('ID')不传第二个参数时,默认读取当前全局登录用户的ID。如果文章是定时发布、或者由后台自动流程触发发布,不存在全局登录用户,这里拿到的作者信息会失效,正确方式是直接从文章对象中取$post->post_author作为作者ID。
修复后的完整代码
function mkto_new_post( $new_status, $old_status, $post ){ if ('publish' === $new_status && 'publish' !== $old_status ){ // 新增过滤:排除修订版、自动草稿,仅处理公开的post类型文章,可根据需求调整post_type if ( wp_is_post_revision( $post->ID ) || $post->post_type !== 'post' || 'publish' !== get_post_status( $post->ID ) ) { return; } // 修正作者ID获取逻辑 $author_id = $post->post_author; $replyEmail = get_the_author_meta('user_email', $author_id); $fromName = get_the_author_meta('display_name', $author_id); $title = $post->post_title; $excerpt = $post->post_excerpt; $id = $post->ID; // 新增特色图默认值兜底,不需要可以删掉?:及后面的内容 $image = get_the_post_thumbnail_url($id) ?: '你的默认特色图地址'; $description = "Email created from post: {$title}"; $subject = "New blog post from {$fromName}: {$title}"; $postFields = "name={$description}&template=1350&folder=%7B%22id%22%3A%221761%22%2C%22type%22%3A%22Program%22%7D&subject={$subject}&fromName={$fromName}&fromEmail={$replyEmail}&replyEmail={$replyEmail}&description={$description}"; $token = mkto_get_token(); $url = "https://monkeyfoo.mktorest.com/rest/asset/v1/emails.json?access_token={$token}"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $postFields, CURLOPT_HTTPHEADER => array( 'Content-Type: application/x-www-form-urlencoded' ), )); $response = curl_exec($curl); curl_close($curl); $data = json_decode($response, true); $emailID = $data['result'][0]['id']; mkto_update_title($emailID, $token, $title); mkto_update_content($emailID, $token, $excerpt, $image); } } // 调高优先级避免其他代码篡改$post参数 add_action('transition_post_status', 'mkto_new_post', 99, 3);
调试建议
如果修改后仍然存在问题,可以在拿到$id后增加日志记录:
error_log( '当前处理文章ID:' . $id . ',文章类型:' . $post->post_type );
开启WordPress debug模式后,通过日志即可明确触发时拿到的文章是否为正常的公开文章,快速定位问题。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

