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

基于ACF字段重写WordPress文章Slug的问题求助

问题根源分析

内存限制错误是因为无限循环导致的:调用wp_update_post时会再次触发save_post钩子,你的update_post_slug函数会重复执行,反复调用wp_update_post直到内存耗尽。此外,直接在post_name中写入斜杠也是不合理的——WordPress会将斜杠识别为URL层级,无法直接作为slug的一部分。

解决方案

1. 修复Slug更新函数(避免循环+确保ID已生成)

调整函数优先级,添加防循环标记,同时确保id_contenido字段已被ACF生成:

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

    if ($post->post_type == 'post' && $post->post_status == 'publish') {
        // 静态变量标记,防止无限循环
        static $processing = false;
        if ($processing) return;
        $processing = true;

        // 获取ACF生成的id_contenido(确保字段已存在)
        $id_contenido = get_field('id_contenido', $post_id);
        if (empty($id_contenido)) {
            $processing = false;
            return;
        }

        $post_slug = sanitize_title($post->post_title);
        // 用短横线连接ID和标题,避免斜杠导致的层级问题
        $new_slug = "{$id_contenido}-{$post_slug}";

        // 更新文章slug
        wp_update_post([
            'ID' => $post_id,
            'post_name' => $new_slug,
        ]);

        $processing = false;
    }
}
// 优先级设为25,确保在ACF的save_post动作(优先级20)之后执行
add_action('save_post', 'update_post_slug', 25, 3);

2. 添加自定义重写规则实现目标URL格式

通过重写规则让domain.com/$id_contenido/$posttitle指向对应文章:

// 注册重写规则
function custom_permalink_rewrite() {
    add_rewrite_rule(
        '^(\d+)/([^/]+)/?$',
        'index.php?post_type=post&name=$matches[2]',
        'top'
    );
}
add_action('init', 'custom_permalink_rewrite');

// 过滤文章链接输出,显示为目标格式
function custom_post_permalink($permalink, $post) {
    if ($post->post_type == 'post' && get_post_status($post) == 'publish') {
        $id_contenido = get_field('id_contenido', $post->ID);
        if (!empty($id_contenido)) {
            $post_slug = sanitize_title($post->post_title);
            return home_url("/{$id_contenido}/{$post_slug}/");
        }
    }
    return $permalink;
}
add_filter('post_link', 'custom_post_permalink', 10, 2);

3. 最后一步:刷新重写规则

登录WordPress后台,进入设置 > 固定链接页面,无需修改任何设置,直接点击「保存更改」,触发重写规则刷新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:23:24