[Soft Reject] Inline style.

I just got this on a theme.
1.Scripts and styles should not be hardcoded anywhere in your theme or added any other way but with wp_enqueue_* hook and to be added from the functions file. This includes custom JS/CSS.
For inline styles use: https://developer.wordpress.org/reference/functions/wp_add_inline_style/ and for scripts https://developer.wordpress.org/reference/functions/wp_add_inline_script/

This is caused by the fact that I give the users the ability to customize some of the shortcode elements like adding some margin or change the color of some text.

This is how I do this:

$margin_top = ( !(empty( $margin_top ))) ? 'margin-top:'. $margin_top.'px;' : null; $margin_bottom = ( !(empty( $margin_bottom ))) ? 'margin-bottom:'. $margin_bottom.'px;' : null; $el_style = ( !empty( $margin_bottom) || !empty( $margin_top ) ) ? 'style="'. esc_attr( $margin_bottom . $margin_top) .'"' : ''; <div class="section-heading '. esc_attr( $alignment . ' ' . $el_class ) .'" '. $el_style.'></div>

Is there any way to do this without usign inline style? wp_add_inline_style dosen’t really works on shortcodes.

How can I achieve the same result as the one above?
The style to be applied only on a specific iteration of an shortcode.

Hello,
If you really think wp_add_inline_style isn’t working for you then you can use a little jQuery here like:
< section data-top-margin=“Your Value” data-bottom-margin=“Your Value”></ section>
jQuery(‘section,div,p,span,h1,h2,h3,h4,h5,h6,a,ul’).each(function(){
var mTop = jQuery(this).attr(“data-margin-top”);
if(mTop){
jQuery(this).css(“margin-top”, “” + mTop + “px;”);
}
});

Thank You

My solution for this was:

  1. Assign shortcode html wrapper an ID.
  2. Generate custom CSS for that ID
  3. Store generated CSS in a PHP global variable, or better in a static class property
  4. Use wp_add_inline_styles to add stored CSS

if( !function_exists( 'videobox_inline_styles' ) ) {

	function videobox_inline_styles(){	
        wp_add_inline_style( 'videobox-collected-styles', videobox_Layout_Compilator::$inline_styles );
	}	
    add_action( 'wp_enqueue_scripts', 'videobox_inline_styles' );
}

In Shortcodes:

/**
 * Example:
 */
$css = "#element-$element_id { background-color: $options['background_color']; }";

videobox_Layout_Compilator::$inline_styles .= $css;

I tried this method. But it only works once the shortcodes are processed and therefore the inline styles are rendered on the <body> which causes a validation error.

Does anybody has a method to add inline styles from shortcodes on the <head> ?

Old topic