admin管理员组

文章数量:1334823

My previous blog author using his font-family and size on every sentence of blog post. I want apply new css rule to post but it cant overide these in-line styles.

I tried searching around and found this one:

add_filter( 'the_content', function( $content ){
  return str_replace( ' style="', ' data-style="', $content);
});

But it removing style of whole website. I just want remove style that used on single post's content only.

My previous blog author using his font-family and size on every sentence of blog post. I want apply new css rule to post but it cant overide these in-line styles.

I tried searching around and found this one:

add_filter( 'the_content', function( $content ){
  return str_replace( ' style="', ' data-style="', $content);
});

But it removing style of whole website. I just want remove style that used on single post's content only.

Share Improve this question asked May 30, 2020 at 3:44 Hiển HồHiển Hồ 32 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

You want to remove the style from single post. And the "single post" term is confusing. Whether you need it for a single post or the single post template.

In either case you have to use your code with conditional and your code may look like this.

If you want to remove from all posts(not pages but including custom post types).

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

    if(is_single()){

        return str_replace( ' style="', ' data-style="', $content); 

    }

    else{

       return $content;

    }

}); 

If you want to remove from all posts(only WordPress post, not custom post type or pages).

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

    if (is_singular('post')) {

          return str_replace( ' style="', ' data-style="', $content);

    }  
    else{

       return $content;

    }
}); 

is_singular is the WordPress API conditional to check post types. https://developer.wordpress/reference/functions/is_singular/

If you want to remove from only one particular post.

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

    if(is_single([POST-ID])){

          return str_replace( ' style="', ' data-style="', $content);

    }
    else{

       return $content;

    }
}); 

You can try this code it works better

add_filter('the_content', function( $content ){
    $content = preg_replace('/ style=("|\')(.*?)("|\')/','',$content);
    return $content;
}, 20);

本文标签: cssHow to remove inline style of Wordpress39s post content only