没有不值得去解决的问题,也没有不值得去学习的技术!

Migrate WordPress Classic Editor Code Blocks Without Loss: Convert SyntaxHighlighter Shortcodes to Gutenberg Blocks in Bulk

1. Identifying the Problem

Recently, while using the Polylang + AutoPoly plugins to translate my blog into multiple languages, I noticed a strange issue:

– Code blocks inserted using the Gutenberg editor (SyntaxHighlighter blocks) retained their formatting perfectly in the translated English articles; indentation and angle brackets remained intact.

– However, code blocks inserted via shortcodes in the classic editor, such as `php`, suffered severe issues after translation: angle brackets were escaped to `<` and `>`, indentation was lost, and the code structure was even broken. (See Figures 1 and 2)

Code blocks inserted via shortcodes in the classic editor, such as `[php]...[/php]`, suffered severe issues after translation: angle brackets were escaped to `<` and `>`, indentation was lost, and the code structure was even broken. (See Figure 1)

Code blocks inserted via shortcodes in the classic editor, such as `[php]...[/php]`, suffered severe issues after translation: angle brackets were escaped to `<` and `>`, indentation was lost, and the code structure was even broken. (See Figure 2)

Through comparative analysis, I found the root cause: when parsing post content, the AutoPoly translation plugin correctly recognizes Gutenberg block markers (

wp:syntaxhighlighter/code

) and therefore does not translate or escape the internal code; however, for shortcodes in the classic editor (such as `php`), the plugin cannot accurately determine their boundaries. It attempts to translate the content inside the shortcodes, which breaks the code. (See Figure 3)

For shortcodes in the classic editor (such as `[php][/php]`), the plugin cannot accurately determine their boundaries. It attempts to translate the content inside the shortcodes, which breaks the code. (See Figure 3)

2. Manually Verifying the Replacement Approach

To confirm whether the solution was viable, I decided to manually test it on a single post first. I selected a Chinese post containing a `php` code block and manually replaced the shortcode with Gutenberg block markers in the code editor.

The original shortcode format: (See Figure 4)

The original shortcode format: (See Figure 4)

The replaced Gutenberg block markers: (See Figure 5)

The replaced Gutenberg block markers: (See Figure 5)

After saving the post, I deleted the corresponding English article and had AutoPoly re-translate it. The results were satisfactory: in the newly generated English article, the code block formatting was completely identical to the Chinese version, with no escaping or corruption. (See Figures 7 and 9)

After saving the post, I deleted the corresponding English article and had AutoPoly re-translate it. The results were satisfactory: in the newly generated English article, the code block formatting was completely identical to the Chinese version, with no escaping or corruption. (See Figure 7)

After saving the post, I deleted the corresponding English article and had AutoPoly re-translate it. The results were satisfactory: in the newly generated English article, the code block formatting was completely identical to the Chinese version, with no escaping or corruption. (See Figure 7)

I also performed the same manual test with shortcodes like python, go, and text, and all passed. This proves that replacing shortcodes with Gutenberg block markers completely resolves the issue of code blocks being broken during translation.

However, I have hundreds of posts using the classic editor, so replacing them one by one manually is impractical. I decided to write a batch processing solution. After some research, I implemented a “PHP function + WordPress bulk action” method, which allows me to manually select the posts to convert from the post list page and complete the replacement with a single click.

Below, I am sharing the complete solution.

3. Solution Overview

Batch convert all SyntaxHighlighter shortcodes (such as php, python) in posts to Gutenberg block markers, and then let the translation plugin regenerate the English articles. This method supports 30+ programming languages and automatically handles alias mapping (e.g., golang → go, javascript → js).

4. Operation Steps

Step 1: Back up the database (very important)

Before performing any bulk operations, make sure to back up your WordPress database. It is recommended to use the UpdraftPlus plugin or export via phpMyAdmin in your hosting control panel.

Step 2: Add the following code to your theme’s functions.php

Log in to the WordPress dashboard, go to Appearance → Theme File Editor, find the functions.php file, and paste the following code at the end of the file (Note: if the file already ends with a ?> tag, place the code before the ?>). (See Figure 12)

Log in to the WordPress dashboard, go to Appearance → Theme File Editor, find the functions.php file, and paste the following code at the end of the file (Note: if the file already ends with a ?> tag, place the code before the ?>). (See Figure 12)
PHP
// 添加批量操作选项
function add_bulk_operation_convert_shortcode( $bulk_actions ) {
    $bulk_actions['convert_shortcode_to_block'] = '转换短代码为区块';
    return $bulk_actions;
}
add_filter( 'bulk_actions-edit-post', 'add_bulk_operation_convert_shortcode' );

function handle_bulk_operation_convert_shortcode( $sendback, $action, $post_ids ) {
    if ( $action !== 'convert_shortcode_to_block' ) return $sendback;
    global $wpdb;
    
    $languages = ['bash','shell','cpp','c','css','go','golang','java','js','javascript','perl','pl','php','plain','text','ps','powershell','python','ruby','sql','xml','xhtml','html','yaml','lua'];
    $converted_count = 0;
    $skipped_count = 0;
    
    foreach ( $post_ids as $post_id ) {
        $post = get_post( $post_id );
        if ( ! $post ) continue;
        
        $old_content = $post->post_content;
        $new_content = $old_content;
        $changed = false;
        
        foreach ( $languages as $lang ) {
            $open  = '[' . $lang . ']';
            $close = '[/' . $lang . ']';
            $pos = 0;
            while ( ($open_pos = strpos( $new_content, $open, $pos )) !== false ) {
                $close_pos = strpos( $new_content, $close, $open_pos );
                if ( $close_pos === false ) break;
                
                $code_start = $open_pos + strlen( $open );
                $code = substr( $new_content, $code_start, $close_pos - $code_start );
                $code = html_entity_decode( $code, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
                
                if ( in_array( $lang, ['text','plain'] ) ) {
                    $block = "<!-- wp:syntaxhighlighter/code -->\n<pre class=\"wp-block-syntaxhighlighter-code\">\n{$code}\n</pre>\n<!-- /wp:syntaxhighlighter/code -->";
                } else {
                    $alias = $lang;
                    if ( $alias === 'golang' )    $alias = 'go';
                    if ( $alias === 'javascript' ) $alias = 'js';
                    if ( $alias === 'pl' )        $alias = 'perl';
                    $block = "<!-- wp:syntaxhighlighter/code {\"language\":\"{$alias}\"} -->\n<pre class=\"wp-block-syntaxhighlighter-code\">\n{$code}\n</pre>\n<!-- /wp:syntaxhighlighter/code -->";
                }
                
                $new_content = substr_replace( $new_content, $block, $open_pos, $close_pos + strlen( $close ) - $open_pos );
                $changed = true;
                $pos = $open_pos + strlen( $block );
            }
        }
        
        if ( $changed ) {
            $wpdb->update( $wpdb->posts, ['post_content' => $new_content], ['ID' => $post_id], ['%s'], ['%d'] );
            $converted_count++;
        } else {
            $skipped_count++;
        }
    }
    
    $sendback = add_query_arg( ['converted_count' => $converted_count, 'skipped_count' => $skipped_count], $sendback );
    return $sendback;
}
add_filter( 'handle_bulk_actions-edit-post', 'handle_bulk_operation_convert_shortcode', 10, 3 );

function bulk_operation_convert_shortcode_notices() {
    if ( isset( $_REQUEST['converted_count'] ) || isset( $_REQUEST['skipped_count'] ) ) {
        $converted = intval( $_REQUEST['converted_count'] ?? 0 );
        $skipped   = intval( $_REQUEST['skipped_count'] ?? 0 );
        echo '<div class="notice notice-success is-dismissible"><p>' .
             sprintf( '转换完成!%d 篇文章已更新,%d 篇文章无需更新。', $converted, $skipped ) .
             '</p></div>';
    }
}
add_action( 'admin_notices', 'bulk_operation_convert_shortcode_notices' );

Update the file.

Step 3: Perform the bulk conversion on the post list page

1. Refresh the “All Posts” page in the WordPress dashboard.

2. Check the posts you need to convert (multiple selections allowed). (See Figure 13)

3. In the “Bulk actions” dropdown menu at the top, select “Convert shortcodes to blocks”.

4. Click the “Apply” button.

Check the posts you need to convert (multiple selections allowed). (See Figure 13)

The system will process this automatically. Once completed, the conversion result will be displayed at the top of the page (e.g., Conversion complete! 1 post updated, 0 posts did not need updating.).

Step 4: Troubleshooting log: Backslash loss and double escaping of `>`

While implementing the bulk conversion, I encountered three typical “pitfalls” that took some time to fully resolve. I am documenting them here to help readers who encounter similar issues.

Pitfall 1: The backslash `\` mysteriously disappears

My test post contained a PowerShell path: `PS E:\wwwroot\object> bash test.sh`. After executing the bulk conversion, all backslashes disappeared, turning it into `PS E:wwwrootobject> bash test.sh`.

After repeated investigation, I found the cause was twofold:

1. Regular expressions: When using `preg_replace_callback` with `(.*?)` to capture code content, PHP’s regex engine escapes backslashes. If the original content contains combinations like `\w`, they might be interpreted as escape sequences and lost.

2. WordPress automatic escaping: When saving a post using `wp_update_post`, WordPress automatically calls `wp_slash` to escape backslashes in the content again, resulting in double backslashes or direct loss upon saving.

Solution: Abandon regular expressions and switch to `strpos` + `substr_replace` for string search and replacement. At the same time, use `$wpdb->update` to write directly to the database, completely bypassing the automatic escaping mechanism of `wp_update_post`.

Pitfall 2: `>` becomes `&gt;`

The common `>` (representing the greater-than sign) in code blocks turned into `&gt;` after conversion, and the browser displayed the literal text `>` instead of `>`.

The reason is that the `>` in the original post content is an HTML entity. When saving to the database, WordPress or the browser escapes the `&` character into `&`, causing double escaping.

Solution: Before generating the Gutenberg block, run `html_entity_decode` on the captured code content to restore all HTML entities to their original characters. This way, after saving, `>` becomes `>`, and the browser can correctly display it as `>`.

Key points of the final code:
– String search and replacement (avoids regex backslash issues)
– `html_entity_decode` (resolves double escaping of entities)
– `$wpdb->update` (bypasses WordPress automatic slashing)

After these corrections, the bulk-converted code blocks retained their formatting perfectly, and backslashes and special symbols were correctly preserved.

Pitfall 3: The code block formatting after bulk conversion met expectations, but `wp-block-syntaxhighlighter-code` was displayed inside some code blocks on the webpage. When checking in the code editor, no issues were found. See Figure 16.

The code block formatting after bulk conversion met expectations, but `wp-block-syntaxhighlighter-code` was displayed inside some code blocks on the webpage. When checking in the code editor, no issues were found. See Figure 16.

Viewing it in the visual editor prompted: This block contains unexpected or invalid content. Clicking Attempt Recovery resulted in recovered code that did not match the original code.

The original code is as follows:

PHP
<?php
 
use yii\db\Migration;
 
/**
 * Class m180620_105204_update_table_options_to_log
 */
class m180620_105204_update_table_options_to_log extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB';
            $this->execute('ALTER TABLE {{%user}} ROW_FORMAT=DYNAMIC');
            $this->execute('ALTER TABLE {{%user}} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
            $this->execute('ALTER TABLE {{%log}} ROW_FORMAT=DYNAMIC');
            $this->execute('ALTER TABLE {{%log}} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
        }
 
        $this->addCommentOnTable('{{%user}}', '用户', $tableOptions);
        $this->addCommentOnTable('{{%log}}', '日志', $tableOptions);
    }
 
    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        echo "m180620_105204_update_table_options_to_log cannot be reverted.\n";
 
        return false;
    }
 
    /*
    // Use up()/down() to run migration code without a transaction.
    public function up()
    {
 
    }
 
    public function down()
    {
        echo "m180620_105204_update_table_options_to_log cannot be reverted.\n";
 
        return false;
    }
    */
}

The recovered code is as follows, with some code missing:

PHP
db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB';
            $this->execute('ALTER TABLE {{%user}} ROW_FORMAT=DYNAMIC');
            $this->execute('ALTER TABLE {{%user}} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
            $this->execute('ALTER TABLE {{%log}} ROW_FORMAT=DYNAMIC');
            $this->execute('ALTER TABLE {{%log}} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
        }

        $this->addCommentOnTable('{{%user}}', '用户', $tableOptions);
        $this->addCommentOnTable('{{%log}}', '日志', $tableOptions);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        echo "m180620_105204_update_table_options_to_log cannot be reverted.\n";

        return false;
    }

    /*
    // Use up()/down() to run migration code without a transaction.
    public function up()
    {

    }

    public function down()
    {
        echo "m180620_105204_update_table_options_to_log cannot be reverted.\n";

        return false;
    }
    */
}



The temporary workaround is to copy the original code from the webpage source code into the visual editor and save it.

Step 5: Remove the temporary code

After the bulk conversion is complete, be sure to go back to functions.php and delete all the code you just added. This has two benefits:

– Prevents accidental operations in the future;

– Keeps the theme files clean.

Step 6: Regenerate translated articles

If you are using Polylang + AutoPoly:

1. Delete the English articles that previously had shortcode issues (or move them to the trash).

2. Re-run the translation (AutoPoly will automatically generate the English version based on the new Chinese post content).

3. You will now find that the code block formatting in the English articles is completely identical to the Chinese version, and escaping or corruption issues no longer occur.

5. Supported Language List

The code already includes the following languages (you can add or remove them as needed):

bash, shell, cpp, c, css, go, golang, java, js, javascript, perl, pl, php, plain, text, ps, powershell, python, ruby, sql, xml, xhtml, html, yaml, lua

Note: plain and text will be converted to plain text blocks without a specified language attribute; golang is automatically mapped to go, javascript to js, and pl to perl.

6. Frequently Asked Questions

Q1: The post content hasn’t changed after performing the bulk operation?

The post itself might not use shortcodes, or the shortcode’s language tag might not be in the supported list. You can check the $languages variable in the code to ensure all the tags you use are included.

Q2: Syntax highlighting in the converted code blocks stopped working?

Please ensure that the SyntaxHighlighter Evolved plugin is still installed and that the version supports Gutenberg blocks. This plugin has been compatible with the block editor since version 3.x.

Q3: What if my code blocks use a format like code without a language tag?

You can change the language list in the code to code, and then handle them uniformly as blocks without a language attribute in the replacement callback.

Q4: Can I only replace posts under a specific category?

Yes. In Step 3, when “checking posts”, you can first filter by category, then select all on the current page, and finally perform the bulk operation.

7. Summary

Using PHP functions + native WordPress bulk actions, we achieved precise, batch conversion of SyntaxHighlighter shortcodes in the classic editor. The entire process requires no additional plugins, is safe and controllable, and perfectly resolves the issue of code block formatting corruption during multilingual translation.

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系