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

如何修改PHP正则,提取WordPress文章中含bouture.com的首个链接

提取WordPress文章中含bouture.com的首个链接到自定义字段

修改正则匹配规则

要只提取包含bouture.com的首个链接,用preg_match即可(仅取第一个匹配项,效率更高),对应的正则表达式如下:

/<a\s+[^>]*href=["']([^"']*bouture\.com[^"']*)["'][^>]*>/i

完整实现代码

将以下代码添加到主题的functions.php文件或自定义插件中:

function extract_bouture_link_to_custom_field($post_id) {
    // 跳过自动保存和修订版本
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;

    // 获取文章内容
    $post_content = get_post_field('post_content', $post_id);
    if (empty($post_content)) return;

    // 匹配含bouture.com的首个链接
    $pattern = '/<a\s+[^>]*href=["\']([^"\']*bouture\.com[^"\']*)["\'][^>]*>/i';
    if (preg_match($pattern, $post_content, $matches)) {
        // 清理URL格式
        $valid_link = esc_url_raw($matches[1]);
        // 更新自定义字段(字段名可自行修改)
        update_post_meta($post_id, 'first_bouture_link', $valid_link);
    } else {
        // 无匹配时删除自定义字段(可选操作)
        delete_post_meta($post_id, 'first_bouture_link');
    }
}
add_action('save_post', 'extract_bouture_link_to_custom_field');

关键说明

  1. 正则逻辑:

    • <a\s+[^>]*:匹配<a>标签起始部分,跳过标签内其他属性
    • href=["']:兼容单双引号包裹的href属性
    • ([^"']*bouture\.com[^"']*):捕获包含bouture.com的完整URL,确保只提取href内的内容
    • /i:不区分大小写,避免因URL大小写差异漏匹配
  2. 代码逻辑:

    • 绑定save_post钩子,在文章保存/更新时自动执行
    • 排除自动保存和修订版本,避免不必要的重复处理
    • 用esc_url_raw处理URL,保证格式安全合规
    • 自动更新或清理自定义字段,保持数据同步

内容的提问来源于stack exchange,提问作者Jonathan - Service Web ARYUP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:47:12