By default, after publishing codes, the post shows a html like this,

<pre class="wp-block-code">
        some codes here

I have plenty posts with codes and don't want to edit them one by one. How do I add a custom class attribute globally for all posts? to make it look like this

<pre class="wp-block-code custom-class">
        some codes here

Thanks in advance.

  • On the right of the editor, there should be an "Advanced" tab. Open that and there'll be an "Additional CSS Class(es)" field. Commented May 7, 2020 at 7:19
  • Okay. Any other solution so that it works globally for all posts without editing one by one?
    – ooneland
    Commented May 7, 2020 at 7:36
  • After deploying the code, I got an error saying, Parse error: syntax error, unexpected ',', expecting variable(T_VARIABLE)
    – ooneland
    Commented May 8, 2020 at 7:18
  • The code in that answer is JavaScript, not PHP. Commented May 8, 2020 at 7:20
  • oops, where should I use that code
    – ooneland
    Commented May 8, 2020 at 7:24

1 Answer 1


To add your custom class to the old posts at once, you can do this via "the_content" filter and using preg_replace or preg_replace_callback function to do a REGEX replacement.

A working Example:

add_filter( 'the_content', function( $content ){

    // Don't do anything if we're not in a single post
    if(! is_singular()){
        return $content;

    $customClass = 'custom-class';

    return preg_replace_callback(
        function( $matches )use( $customClass ){
            return '<pre' . $matches[1] . 'class="' . trim($matches[2]) . ' ' . $customClass . '"';

} );

Not the answer you're looking for? Browse other questions tagged or ask your own question.