2017-07-30 108 views
0

目前我正在開發一個插件,它連接到內容編輯器。我的回調在編輯後接收了發佈的內容並調用了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也不會改變任何內容。我是否使用正確的過濾器?

回答

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將短代碼括號內的所有單個轉義引號轉換回普通引號,第二個轉換括號內的所有雙轉義引號。這樣內容保持不變,這減少了代碼注入的機會。

PHP Manual on preg_replace

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; 
} 

請隨時加強這方面的答案。