最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

posts - How to add a custom class attribute into code wrapper?

programmeradmin1浏览0评论
This question already has answers here: How to add a custom CSS class to core blocks in Gutenberg editor? (3 answers) Closed 4 years ago.

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

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

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">
    <code>
        some codes here
    </code>
</pre>

Thanks in advance.

This question already has answers here: How to add a custom CSS class to core blocks in Gutenberg editor? (3 answers) Closed 4 years ago.

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

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

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">
    <code>
        some codes here
    </code>
</pre>

Thanks in advance.

Share Improve this question edited May 7, 2020 at 7:40 ooneland asked May 7, 2020 at 6:44 oonelandooneland 93 bronze badges 7
  • On the right of the editor, there should be an "Advanced" tab. Open that and there'll be an "Additional CSS Class(es)" field. – Jacob Peattie 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. – Jacob Peattie Commented May 8, 2020 at 7:20
  • oops, where should I use that code – ooneland Commented May 8, 2020 at 7:24
 |  Show 2 more comments

1 Answer 1

Reset to default 0

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(
        '/<pre([^>]+)class="([^"]+)"/i',
        function( $matches )use( $customClass ){
            return '<pre' . $matches[1] . 'class="' . trim($matches[2]) . ' ' . $customClass . '"';
        },
        $content
    );

} );
发布评论

评论列表(0)

  1. 暂无评论