首先,创建一个使用get_shortcode_regex
获取替换了短代码的帖子的帖子内容。
请注意,任何其他shoertcode都将保持不变
function get_replaced_sourcecode_sc( $post ) {
if ( empty($post) ) global $post;
if ( empty($post) || ! isset($post->post_content) ) return false;
$content = $post->post_content;
if (
preg_match_all( \'/\'. get_shortcode_regex() .\'/s\', $post->post_content, $matches )
&& array_key_exists( 2, $matches ) && in_array( \'sourcecode\', $matches[2] )
) {
foreach ( $matches[2] as $i => $sc ) {
if ( $sc == \'sourcecode\' )
$now = $matches[0][$i];
$replace = do_shortcode($now);
$content = str_replace( $now, $replace, $content );
}
}
return $content;
}
现在在您的
functions.php
您还可以添加以下代码:
function replaced_sourcecode_sc_all() {
$already = get_transient(\'replaced_sourcecode\') ? : array();
$all = get_posts(\'nopaging=1post_type=post\');
if ( ! empty($all) ) {
if ( count($all) == count($already) ) {
error_log(\'replaced_sourcecode_sc_all already done its work\');
return;
}
$done = array();
foreach ( $all as $one ) {
if ( in_array($one->ID, $already) ) continue;
$content = get_replaced_sourcecode_sc( $post );
$post = array(\'ID\' => $one->ID, \'post_content\' => $content);
$do = wp_update_post( $post );
if ( $do ) $done[] = $do;
}
set_transient(\'replaced_sourcecode\', $done);
}
}
add_action(\'shutdown\', \'replaced_sourcecode_sc_all\');
现在,启用WP日志记录,然后访问您的站点2到3次。检查错误日志,如果您发现字符串“replaced\\u sourcecode\\u sc\\u all have done it works”,您可以删除该函数(或者简单地注释掉“add\\u action”行)。