我最近发布了一个插件, WP CODA滑块, ,它使用短代码将jQuery滑块添加到任何帖子或页面上。我正在下一个版本中添加一个选项页面,我想包括一些CSS选项,但我不希望插件将样式选择添加为内联CSS。我希望将选项动态添加到CSS文件中。

我还想避免使用fopen或写入文件以解决安全问题。

像这样的事情很容易完成,还是只将样式选择直接添加到页面上,我会更好?

有帮助吗?

解决方案

利用 wp_register_stylewp_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启动了两次,并运行所有数据库查询两次,这是一个很大的混乱。

如果您的滑块仅在一页上,并且您希望动态设置样式,那么最好的选择就是在标题中添加样式块。

按照性能顺序:

  1. 在标题中添加小块样式,动态创建 - 非常快
  2. 通过wp_enqueue_style添加非动态样式表 - 媒体
  3. 通过wp_enqueue_style添加动态样式表 - 非常慢

这就是我通常这样做的方式:

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' );
许可以下: CC-BY-SA归因
scroll top