如何在wordpress短代码中添加内联css / js

时间:2016-08-14 08:26:56

标签: javascript css wordpress shortcode

我正在创建一个短代码,用于根据情况为该短代码动态更改css和js。现在的问题是我没有弄清楚如何在add_action()中使用add_shortcode()。让我给你一个示例代码段,以便你们可以更好地理解我:

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>';
    });

});

现在显然它不起作用,所以我希望你们中的任何人能够以正确的方式指导我如何做类似的事情。

如果可以,请帮助而不是否定投票。

1 个答案:

答案 0 :(得分:0)

应该有更好的方法来做到这一点,但目前只是让它工作,删除add_action()部分,只需用你的代码创建一个字符串并将其返回:

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;
});