Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
// 保存時 shortcode の書き換え
add_filter('wp_insert_post_data', 'rewrite_shortcode_insert_post_data');
function rewrite_shortcode_insert_post_data($data) {
// foo shortcode がなければ書き換えなし
if (false === has_shortcode($data['post_content'], 'foo')) {
return $data;
}
// foo shortcode 部分の書き換え
$pattern = get_shortcode_regex();
// shortcode 部分を繰り返し取得して置換
$data['post_content'] = preg_replace_callback('/'. $pattern .'/s', function ($matches) {
// foo 以外の shortcode は書き換えなし
if ($matches[2] !== 'foo') {
return $matches[0];
}
// エスケープされた shortcode は書き換えなし
if ($matches[1] == '[' && $matches[6] == ']') {
return $matches[0];
}
// shortcode のパラメータ取得
$atts = shortcode_parse_atts(stripslashes($matches[3]));
// baz !== null (規定値以外)の場合も書き換えなし
if ($atts['baz'] !== null) {
return $matches[0];
}
// baz が既定値以外の場合 shortcode を書き換え
$atts['baz'] = uniqid();
$params = array();
foreach ($atts as $key => $val) {
$params[] = "$key=\"$val\"";
}
return '[foo ' . implode(' ', $params) . ']'; // 書き換えた shortcode
}, $data['post_content']);
return $data;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment