这是我想出的剧本。它循环遍历WordPress实例中的所有帖子,并将其分为三个部分:
短代码行之前的HTML/内容短代码行之后的HTML/内容我决定使用substr()
拆分内容。然后,我将所有内容重新组装到一起,并在中间部分添加“包装”快捷代码。
$args = array( \'numberposts\' => -1, \'post_status\' => \'publish|draft|trash\' )
$posts = get_posts( $args );
if( !empty( $posts ) ){
foreach( $posts as $post ){
$content = $post->post_content;
if( !has_shortcode( $content, \'components\') ){
$pattern = \'/\\[component id=\\"[0-9]+\\"\\]/\';
preg_match_all( $pattern, $content, $matches, PREG_OFFSET_CAPTURE);
$first_match = $matches[0][0];
$first_match_start = $first_match[1]; // Start position of the first match
$last_match = $matches[0][ count($matches[0]) - 1 ];
$last_match_start = $last_match[1];
$last_match_end = $last_match_start + strlen($last_match[0]);
$before_html = substr($content, 0, $first_match_start); // Get all the content before the first match of [component id="XYZ"]
$component_shortcodes = substr($content, $first_match_start, $last_match_end - $first_match_start ); // Get everything in between the first [component id="XYZ"] and the last
$after_html = substr($content, $last_match_end ); // Get everything after the last [component id="XYZ"] match
// Perform the actual wrapping here
$new_content = $before_html . \'[components]\' . $component_shortcodes . \'[/components]\' . $after_html;
$post->post_content = $new_content;
wp_update_post( $post );
}
}
}