php - 通过php将css添加到文件中

标签 php css wordpress

我正在开发一个 WordPress 插件,当有人启用某项功能时,我希望它能够将一些预定义的 CSS 添加到样式表中。

除了常规样式表之外,我不能简单地包含样式表,因为某些功能会与其发生冲突。我希望这样当他们单击一个元素时,它只加载与此相关的 CSS。

当他们选择此元素时,它应该将相关 CSS“打印”到样式表中。

我可以调用我创建的包含 CSS 的函数,并且仅在启用该功能后才会调用该函数吗?

最佳答案

我可以通过几种方法来解决这个问题。

您可以使用内联 css,而不需要主题的样式表。并在条件之间写下您需要的内容,如第一个示例或使用 wp_add_inline_style

想法 1:使用 wp_add_inline_style

//* Load CSS
function yourplugin_prefix_load_css() {
     add_action( 'wp_head', 'yourpluginprefix_css', 15 );
}
add_action( 'plugins_loaded' , 'yourplugin_prefix_load_css' );


//* CSS
function yourpluginprefix_css() {

    //vars
    $a = get_option( 'where_a', 'what_a' );
    $b = get_option( 'where_b', 'what_b' );

    // begin CSS
    $css = '';

    $css .= '<style class="whatever" >';

    //condition $a
    if ( $a == '0' ) :

        $css .= '

            .property{
                display: inline-block;
            }

        '; 

    endif;  //condition for $a


    //condition $b
    if ( $b != '1' ) :

        $css .= '

            .property-something{
                border: 1px solid #333;
            }

        '; 

    endif;  //condition for $b


    //close the style sheet
    $css .= '</style>';

    //minify it
    $css_min = str_replace( array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css );

    echo $css_min;

}   

带有 wp_add_inline_style 的 IDEA 2

或者,您可以使用 wp_add_inline_style 并获取当前主题的句柄。

function pluginprefix_css() {

    //get current theme stylesheet handle
    $current_theme = ( wp_get_theme() );

    //get our values for conditions
    $a             = get_option( 'where_a', 'what_a' );
    $b             = get_option( 'where_b', 'what_b' );


    //begin css
    $css = '';


    //condition $a
    if ( $a == '0' ) :

        $css .= '

            .property{
                display: inline-block;
            }

        '; 

    endif;  //condition for $a


    //condition $b
    if ( $b != '1' ) :

        $css .= '

            .property-something{
                border: 1px solid #333;
            }

        '; 

    endif;  //condition for $b      


    //minify css
    $css_min = str_replace( array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css );

    //add inline style                
    wp_add_inline_style( $current_theme->stylesheet, $css_min );


}
add_action( 'wp_enqueue_scripts', 'pluginprefix_css' );

关于php - 通过php将css添加到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349076/

相关文章:

php - 从 iis7 中的 wordpress URL 中删除 index.php

php - mysqli_query() : Empty query in line

css - 将元素变成卡片

php - 如何在 CentOS 8 上安装 PHP 7 的 MySQL 扩展?

php - 在 Woocommerce 页面中更改 &lt;title&gt;

php - 用变量中的数字增加变量 + PHP

css - 相同的 CSS,不同的结果(Bootstrap4,仅限 Chrome)

javascript - "[object Object]"为什么我用这段代码得到它?

php - Wordpress - 只有帖子的用户总数

css - 如何定位我的 wordpress 网站上的一个特定页面以显示响应式布局?