Ich möchte vorhandene Shortcodes in Post-Inhalt innerhalb eines neuen Shortcodes, den ich meinem Plugin hinzufüge, einbinden. Der vorhandene Inhalt sieht folgendermaßen aus:
Some text - could be HTML or other shortcodes .... [component id=12] [component id=13] [component id=14] .... Some text - could be HTML or another shortcodes
Ich versuche, ein Skript zu schreiben, das Post für Post gehen wird, extrahieren Sie alle Shortcodes des Formulars [component id=X]
und verpacken Sie sie wie folgt in einen anderen Shortcode:
Some text - could be HTML or other shortcodes .... [components] [component id=12] [component id=13] [component id=14] [/components] .... Some text - could be HTML or another shortcodes
Ich habe Probleme, die Regex dafür zu schreiben. Ich hoffe, preg_replace_callback()
zu verwenden, um dies zu erreichen, aber nicht sicher, ob dies die geeignete function ist oder nicht.
Hier ist das Skript, das ich mir ausgedacht habe. Es durchläuft alle Beiträge in einer WordPress-Instanz und teilt sie in drei Abschnitte auf:
Ich entschied mich, substr()
zu verwenden, um den Inhalt zu teilen. Ich stelle dann alles gegen Ende wieder zusammen und füge den “Wrap” -Kurzcode um das Mittelstück ein.
$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 ); } } }