Files
wordpress-kratos-yang/inc/theme-custom-code.php
T
laoyang eaabc7717f 把自定义样式从主题目录搬到主题选项,升级不再丢
原来主题里有个 custom/ 目录(custom.css / custom.js / custom.php),
是给用户随手加样式的入口。问题是它位于主题目录内,而 WordPress 升级
主题的做法是把整个主题目录删掉再解压(class-theme-upgrader.php 里
clear_destination = true,随后 delete_old_theme() 递归删除),
所以每次升级这些文件都会丢。custom.php 还会被 require,
等于在主题里留了一个执行任意 PHP 的口子。

改成后台选项:
- 主题选项新增「自定义代码」组,含自定义 CSS / 自定义 JS 两个输入框
- 内容存在数据库的 kratos 选项里,与主题文件解耦,升级、重装都不影响
- 分别在主题样式和主题脚本之后加载,优先级最高

为此新增了 code 字段类型,没有复用 textarea:textarea 的 sanitizer
走 wp_kses(),CSS 的子选择器 > 和 JS 的 < 会被当成 HTML 标签剥掉,
样式会静默失效。code 类型只去掉 PHP 标签、打断 </style> 和 </script>,
其余原样保留。渲染时也不走公共的 stripslashes —— options.php 已经
wp_unslash 过,再剥一层会把 CSS 的 \f101、JS 的 \n 啃坏。

自定义 CSS 的默认值就是原来 custom.css 的内容,逐字节一致(354 字节),
所以升级瞬间站点外观没有任何变化。清空输入框保存即可彻底去掉。

验证:真实 WP 7.1.3 / PHP 8.5.12 环境 20 条断言全过(含 DB 往返、
子选择器 / 反斜杠保真、危险内容过滤),生产选项指纹前后一致;
反向注入「默认值改空」能立刻被抓到。
2026-10-23 10:35:56 +08:00

68 lines
1.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 自定义代码(CSS / JS)
*
* 这两段代码存在主题选项里(数据库 wp_options 的 kratos 项),不存主题目录。
* 原因:WordPress 升级/更新主题时会**清空整个主题目录**再解压
* (wp-admin/includes/class-theme-upgrader.php 里 clear_destination = true,
* 随后 delete_old_theme() 递归删除),写在主题目录里的任何自定义文件都会丢。
* 放进选项表就与主题文件解耦,升级、重装、换主题目录名都不影响。
*
* @author Seaton Jiang <seaton@vtrois.com>
* @license MIT License
*/
/**
* 默认自定义 CSS。
*
* 历史沿革:这些规则原本放在主题目录下的一个 custom 子目录里,是该主题早期的
* 「自定义样式」入口。改成配置项后,把它作为默认值,保证切换瞬间站点外观
* 完全不变;同时 `恢复默认` 也能拿回这套样式。
*
* 想彻底清掉:在后台把「自定义 CSS」清空保存即可(空值会覆盖这里的默认值)。
*/
function yang_default_custom_css()
{
return <<<'CSS'
.article .content p{ text-indent:2em }
.k-main .details .article .content h2 {
margin: 16px -16px;
padding: 0 10px;
border-left: 5px solid #00a2ff;
background-color: rgba(243, 243, 243, 0.7);
font-size: 20px;
line-height: 41px;
}
ul{
margin-left:2em;
}
ol{
margin-left:2em;
}
ol > li{
line-height: 1.8;
}
ul > li{
line-height: 1.8;
}
CSS;
}
/**
* 取自定义 CSS(未设置时回退到默认值)
*/
function yang_custom_css()
{
$css = kratos_option('g_custom_css', yang_default_custom_css());
return is_string($css) ? $css : '';
}
/**
* 取自定义 JS(未设置时为空)
*/
function yang_custom_js()
{
$js = kratos_option('g_custom_js', '');
return is_string($js) ? $js : '';
}