简体   繁体   中英

How to add inline css/js inside a wordpress shortcode

I'm working on creating a shortcode which is meant to change the css and js dynamically for that shortcode based on the situation. Now the problem is that I not getting a clue about how to use add_action() inside a add_shortcode() . Let me give you an example snippet code so that you guys can better understand me:

add_shortcode('example', function( $atts ) {
    //extracting the shortcode attributes
    extract( shortcode_atts( array(
        'value1' => null,
        'value2' => null, 
        'value3' => null
    ), $atts ) );

    //Now here I wll do my code for the shortcode
    // But the shortcode needs some js and css to work
    // so, I'm trying like this

    //For the CSS
    add_action('wp_head', function() {
        echo '<style type="text/css">
            .class {
                background-color: '. $value2 .';
            }
        </style>';
    });

    //For the JS
    add_action('wp_footer', function() {
        echo '<script type="text/javascript">
            var a = '. $value3 .'
        </script>';
    });

});

Now obviously it is not working, so I was hoping if any of you can guide me how to the similar thing in the proper way.

If you can, please help instead of negative voting the question.

There should be a better way to do this, but currently to just make it work, remove the add_action() part, just make a string with your code and return it:

add_shortcode('example', function( $atts ) {
    //extracting the shortcode attributes
    extract( shortcode_atts( array(
        'value1' => null,
        'value2' => null, 
        'value3' => null
    ), $atts ) );

    //For the CSS
        $result = '<style type="text/css">
            .class {
                background-color: '. $value2 .';
            }
        </style>';

    //For the JS
        $result .= '<script type="text/javascript">
            var a = '. $value3 .'
        </script>';

    return $result;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM