Question

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.

Was it helpful?

Solution

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.org/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;

    }
}); 

OTHER TIPS

You can try this code it works better

add_filter('the_content', function( $content ){
    $content = preg_replace('/ style=("|\')(.*?)("|\')/','',$content);
    return $content;
}, 20);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top