Home > other >  add CSS with array of variables in head - Wordpress - PHP
add CSS with array of variables in head - Wordpress - PHP

Time:06-18

I'm trying to return css build with multiple variables in my Wordpress website, its kind of working but it's only returning the first array. If i echo instead of return inside the foreach it shows the code correctly but outside the correct location.

Sorry for the bad code and possible definitions about php. I have only just started to learn php.

The code

 function child_custom_color_css4() {
    function child_custom_color_css2() {

        

        function test_loop_1_beta() {
            $boo = 'soortverhaal0 ';
            $foo = 'soortverhaal1 ';
            return array($boo, $foo);
        }

        $loops = test_loop_1_beta();

        
        
        global $nectar_options;

        $Styled=array();
            foreach ($loops as $loop) {
                
                return '
            
                #test-loop.'. $loop .' {
                background-color: '.esc_attr($nectar_options["accent-color"]).' !important;
                }
                
                ';

        }
        return implode($Styled);
        

    }

    $get_arrays = child_custom_color_css2();
    
    wp_add_inline_style( 'main-styles', $get_arrays);
}
add_action('wp_enqueue_scripts','child_custom_color_css4', 20); '''

Output:

<style id="main-styles-inline-css" type="text/css">

        
            #test-loop.soortverhaal0  {
            background-color: #f04e23 !important;
            }
            
</style>

Edit: what need:

<style id="main-styles-inline-css" type="text/css">

            #test-loop.soortverhaal0  {
            background-color: #f04e23 !important;
            }

            #test-loop.soortverhaal1  {
            background-color: #f04e23 !important;
            }
            
</style>

CodePudding user response:

I think you could do something like that:

function child_custom_color_css4() {
    function child_custom_color_css2() {

        $loops = [
          'soortverhaal0 ',
          'soortverhaal0 ',
        ];

        global $nectar_options;

        $styled = [];
        
        foreach ($loops as $loop) {
          $styled[] = '#test-loop.' . $loop . ' { background-color: ' . esc_attr( $nectar_options['accent-color'] ) . ' !important; }';
        };

        return implode("\n",$styled);
        
    }

    $get_arrays = child_custom_color_css2();
    
    wp_add_inline_style( 'main-styles', $get_arrays);
}
add_action('wp_enqueue_scripts','child_custom_color_css4', 20);

I do an array push to acumulate each loop into $style array.

I think you would need to define other separator for the implode function like:

return implode("\n",$styled)
  • Related