防止WordPress转义短代码属性(已解决)
问题描述:
目前我正在开发一个插件,它连接到内容编辑器。我的回调在编辑后接收了发布的内容并调用了do_shortcode(),但是有一个问题,我不知道如何解决它。防止WordPress转义短代码属性(已解决)
add_filter('wp_insert_post_data', 'prepareContentSaving', 99, 2);
add_filter('wp_update_post_data', 'prepareContentSaving', 99, 2);
举例来说,如果我的帖子看起来像(这显然看起来像是有效的简码语法):
[foo bar="two words"]
我的回调接收:
[foo bar=\"two words\"]
看起来正确的,对不对?但现在只要简码通过do_shortcode解析()的参数解析像
[tag argument1=value1 argument2]
,而不是
[tag argument="Foo bar"]
,然后看在PHP是这样的:
array(
[0]=> string "bar=\"two"
[1]=> string "words\""
)
那么如何我可以防止短代码内的引号被转义吗?发布数据钩子有问题吗?将优先级从99更改为0也不会改变任何内容。我是否使用正确的过滤器?
答
WordPress的其实并不功能防止简码进行转义的任何选项。唯一的办法是撤销它把所有“\“”回“””功能‘prepareContentSaving’内(同为单引号):
add_filter('wp_insert_post_data', 'prepareContentSaving', 99, 2);
add_filter('wp_update_post_data', 'prepareContentSaving', 99, 2);
function prepareContentSaving($data, $post) {
$content = $post['post_content'];
$content = correctShortcodeSlashes($content);
... any further processing ...
$data['post_content'] = $content;
return $data;
}
保存后的WordPress不仅逃脱报价后,但也逃避反斜杠。所以'''变成'\''和'\''(如果编辑想要转义引用)变成'\\'''。
第一个给定的PCRE将短代码括号内的所有单个转义引号转换回普通引号,第二个转换括号内的所有双转义引号。这样内容保持不变,这减少了代码注入的机会。
function correct_shortcode_slashes($text) {
$attribute_escaped_slashes_pattern = '/(\[)((.|\s)*?)([^\\\\])\\\\("|\')(.*?)(\])/';
$attribute_escaped_slashes_replacement = '$1$2$4"$6$7';
$attribute_double_slashes_pattern = '/(\[)((.|\s)*?)\\\\+("|\')(.*?)(\])/';
$attribute_double_slashes_replacement = '$1$2"$5$6';
$result = $text;
$counter = 0;
while(true) {
$result = preg_replace($attribute_escaped_slashes_pattern, $attribute_escaped_slashes_replacement, $result, -1, $counter);
if($counter === 0) {
break;
}
}
while(true) {
$result = preg_replace($attribute_double_slashes_pattern, $attribute_double_slashes_replacement, $result, -1, $counter);
if($counter === 0) {
break;
}
}
return $result;
}
请随时加强这方面的答案。
答
你可以尝试修改这样的代码:
$post = array_map('stripslashes_deep', $_POST);
更多信息链接:http://codex.wordpress.org/Function_Reference/stripslashes_deep
谢谢。由于我担心剥离所有反斜杠的安全方面,我会在进一步研究后再回来。 –