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

求通过functions.php自动设置WordPress固定链接的有效代码

实现WordPress主题激活时自动设置固定链接为/%postname%/%category%/

需求说明

我开发的WordPress主题内置了独立用户登录页面,该页面仅在固定链接设置为/%postname%/%category%/时可正常访问。虽然手动通过WordPress后台设置固定链接也能满足需求,但希望实现主题激活时自动覆盖原有设置,直接应用该固定链接格式。此前尝试的代码未生效,后确认直接修改数据库wp_options表中permalink_structure字段的option_value即可达成目标,现寻求可行代码方案。

之前使用的无效代码

/*
 * Set permlinks on theme activate
 */
function set_custom_permalinks() {
    $current_setting = get_option('permalink_structure');

    // Save permalinks to a custom setting, force create of rules file
    global $wp_rewrite;
    update_option("rewrite_rules", FALSE);
    $wp_rewrite->set_permalink_structure('/%postname%/%category%/');
    $wp_rewrite->flush_rules(true);
}
add_action('after_switch_theme', 'set_custom_permalinks');

可行解决方案

直接使用WordPress内置的update_option()函数修改permalink_structure的值即可(该函数本质就是操作wp_options表),同时配合刷新重写规则确保设置立即生效,代码如下:

/**
 * 主题激活时自动设置固定链接并刷新重写规则
 */
function theme_activate_set_permalink() {
    // 目标固定链接结构
    $target_structure = '/%postname%/%category%/';
    
    // 更新固定链接设置(对应修改wp_options表的permalink_structure字段)
    update_option('permalink_structure', $target_structure);
    
    // 强制刷新重写规则,确保新固定链接生效
    global $wp_rewrite;
    $wp_rewrite->flush_rules(true);
}
add_action('after_switch_theme', 'theme_activate_set_permalink');

注意事项

  • 该代码会强制覆盖原有固定链接设置,建议在主题文档中告知用户这一行为,避免造成困惑
  • 刷新重写规则需要WordPress具备.htaccess文件的写入权限(Apache服务器);若使用Nginx,需手动配置对应重写规则
  • 若主题切换后设置未立即生效,可手动刷新一次WordPress后台设置页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:32:37