Skip to navigation
Split wordpress post source code into token of text and shortcode
16.12.25
``` /** * Returns an array: * [0] => array of strings (either plain text or a short-code block) * [1] => array of types ('text' | 'shortcode') */ function wp_split_post_by_shortcodes( $post_content ) { // 1. Protect every short-code (including nested ones) as a single token // Opening tag: [name …] or [name … /] // Closing tag: [/name] $pattern = '/ \[(\[?) # opening bracket ([a-zA-Z0-9_-]+) # short-code name [^\]]*? # any attributes (?:\/?\]|\] # closing bracket (?:.*?\[\/\2\])?) # optional closing tag \s* # optional white-space after /s'; $parts = preg_split( $pattern, $post_content, -1, PREG_SPLIT_DELIM_CAPTURE ); $tokens = array(); $types = array(); $in_shortcode = false; foreach ( $parts as $i => $chunk ) { if ( $i & 1 ) { // odd index → we captured a short-code $tokens[] = $chunk; $types[] = 'shortcode'; $in_shortcode = true; } else { $trimmed = trim( $chunk ); if ( $trimmed !== '' ) { $tokens[] = $trimmed; $types[] = 'text'; } } } return array( $tokens, $types ); } foreach ( $tokens as $i => $token ) { if ( $types[ $i ] === 'text' ) { // Send to Google / DeepL / whatever $tokens[ $i ] = my_translate( $token, 'en', 'fr' ); } // short-code blocks are left untouched } $new_content = implode( '', $tokens ); // Update the post (or save as a new translation) wp_update_post( array( 'ID' => $post_id, 'post_content' => $new_content, ) ); ```
Reply
Anonymous
Information Epoch 1766528946
Use shell scripts to increase leverage and portability.
Home
Notebook
Contact us