我最近发布了一个插件,WP Coda Slider, 它使用短代码将jQuery滑块添加到任何帖子或页面。我在下一个版本中添加了一个选项页面,我想包括一些CSS选项,但我不希望插件将样式选择添加为内联CSS。我希望在调用CSS文件时将这些选项动态添加到该文件中。
我还希望避免使用fopen或写入文件以解决安全问题。
这样的事情很容易完成,还是直接将样式选择添加到页面中更好?
我最近发布了一个插件,WP Coda Slider, 它使用短代码将jQuery滑块添加到任何帖子或页面。我在下一个版本中添加了一个选项页面,我想包括一些CSS选项,但我不希望插件将样式选择添加为内联CSS。我希望在调用CSS文件时将这些选项动态添加到该文件中。
我还希望避免使用fopen或写入文件以解决安全问题。
这样的事情很容易完成,还是直接将样式选择添加到页面中更好?
使用wp_register_style
和wp_enqueue_style
添加样式表。不要简单地将样式表链接添加到wp_head
. 队列样式允许其他插件或主题在必要时修改样式表。
您的样式表可以是。php文件:
wp_register_style(\'myStyleSheet\', \'my-stylesheet.php\');
wp_enqueue_style( \'myStyleSheet\');
my-stylesheet.php 看起来是这样的:<?php
// We\'ll be outputting CSS
header(\'Content-type: text/css\');
include(\'my-plugin-data.php\');
?>
body {
background: <?php echo $my_background_variable; ?>;
font-size: <?php echo $my_font_size; ?>;
}
动态构建一个CSS文件,然后加载它,这给添加CSS文件的带宽非常低的处理增加了巨大的性能负担,特别是如果CSS中有将通过WP处理的变量。因为为一个页面加载创建了两个不同的文件,所以WP启动了两次,并运行了两次所有DB查询,这是一个很大的混乱。
如果您的滑块只在一个页面上,并且希望动态设置样式,那么最好是在页眉中添加样式块。
按性能顺序:
在标题中添加动态创建的小样式块-非常快-通过wp\\u enqueue\\u样式添加非动态样式表-中等-通过wp\\u enqueue\\u样式添加动态样式表-非常慢
我通常是这样做的:
function build_stylesheet_url() {
echo \'<link rel="stylesheet" href="\' . $url . \'stylesheetname.css?build=\' . date( "Ymd", strtotime( \'-24 days\' ) ) . \'" type="text/css" media="screen" />\';
}
function build_stylesheet_content() {
if( isset( $_GET[\'build\'] ) && addslashes( $_GET[\'build\'] ) == date( "Ymd", strtotime( \'-24 days\' ) ) ) {
header("Content-type: text/css");
echo "/* Something */";
define( \'DONOTCACHEPAGE\', 1 ); // don\'t let wp-super-cache cache this page.
die();
}
}
add_action( \'init\', \'build_stylesheet_content\' );
add_action( \'wp_head\', \'build_stylesheet_url\' );
我对这类文章的所有建议都有困难——也许我有点笨,也许投稿人已经失去了共同点。
我决定在插件php文件中对此进行编码:-
echo "<link href=\'http://www.brittany-gite-holidays.co.uk/wp-content/plugins/flexavailability/css/css.css\' type=\'text/css\' rel=\'stylesheet\' />";
echo "<link href=\'http://www.brittany-gite-holidays.co.uk/wp-content/plugins/flexavailability/css/public.css\' rel=\'stylesheet\' type=\'text/css\'/>";
这似乎奏效了。它只加载那些使用插件的页面。它加载在h1标签之后,这对我来说很好。我看不出它如何能更有效或更清晰。。。。。但也许我错了——我确实说过我有点胖。
自Wordpress 3.3更新
有一个函数称为wp_add_inline_style 可用于根据主题/插件选项动态添加样式。这可以用来在头部添加一个小的css文件,这应该是快速有效的。
<?php
function myprefix_scripts() {
wp_enqueue_style(\'name-of-style-css\', plugin_dir_path(__FILE__) . \'/css/ccsfilename.css\');
$css = get_option( \'loader_css\', \'default css goes here for when there is no value\' );
//or for Example
$color = get_option( \'custom_plugin_color\', \'red\' ); //red is default value if value is not set
$css = ".mycolor{
background: {$color};
}";
wp_add_inline_style(\'name-of-style-css\', $css);
}
add_action( \'wp_enqueue_scripts\', \'myprefix_scripts\' );
如何指示wordpress使用“样式”以外的文件名。css“用于我的主样式表-例如,styles-1。css?我想这样做是为了版本控制和缓存。