WordPress如何通过循环提取post_meta的offer字段存储的多个邮箱地址
正确提取offer字段所有邮箱的方案
问题原因
- 语法错误:原错误代码中
custom_fields = get_post_custom($id)漏写了变量前缀$ - 存储结构理解错误:
offer字段存储的是多个base64编码后的序列化字符串,以逗号拼接的整体,并非单个序列化结果 - 循环逻辑错误:单个解码后的offer是仅包含
name/email/message三个键的关联数组,直接遍历该数组会读取每个属性的字符串值,而非遍历多个offer条目,对字符串执行$result['email']操作会被PHP隐式转换为取下标,最终输出乱码。
正确实现代码
global $post; $post = $wp_query->post; $id = $post->ID; // 获取offer字段原始值 $custom_fields = get_post_custom($id); $offer_raw = $custom_fields['offer'][0]; // 按逗号分割得到多个独立的base64编码串 $offer_base64_list = explode(',', $offer_raw); $all_emails = []; foreach ($offer_base64_list as $base64_item) { $base64_item = trim($base64_item); if (empty($base64_item)) continue; // 解码+反序列化得到单个offer数据 $offer_data = unserialize(base64_decode($base64_item)); // 校验邮箱存在且合法再存入结果 if (isset($offer_data['email']) && is_email($offer_data['email'])) { $all_emails[] = $offer_data['email']; } } // 按需输出所有邮箱,示例直接打印 print_r($all_emails);
内容的提问来源于stack exchange,提问作者Sanad
相关产品推荐
相关产品推荐

