我正在开发一个 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/