【问题标题】:WordPress Customizer CSS for Background Image背景图像的 WordPress 定制器 CSS
【发布时间】:2016-11-23 20:53:38
【问题描述】:

我正在使用下面的代码通过 WordPress 定制器的设置将一些 CSS 添加到页面头部:

public static function header_output() {
   ?>
   <!--Customizer CSS--> 
   <style type="text/css">
        <?php self::generate_css('#site-title a', 'color', 'header_textcolor', '#'); ?> 
        <?php self::generate_css('body', 'background-color', 'background_color', '#'); ?> 
        <?php self::generate_css('a', 'color', 'link_textcolor'); ?>
        <?php self::generate_css('#wrapper-1', 'background-color', 'section_1_background_color'); ?>
        <?php self::generate_css('#wrapper-1', 'background-image', 'section_1_background_image'); ?>
   </style> 
   <!--/Customizer CSS-->
   <?php
}

除了背景图像之外,一切都很好,因为它输出:

#wrapper-1 { background-image:filename.jpg; }

代替:

#wrapper-1 { background-image: url("filename.jpg"); }

有谁知道修改下面的 php 行以在图像周围包含 url(" ") 的正确方法?

<?php self::generate_css('#wrapper-1', 'background-image', 'section_1_background_image'); ?>

【问题讨论】:

  • 您是否有包含 generate_css 函数的自定义主题自定义类?看起来默认情况下只包含一个 sprintf 调用以形成 css,这意味着如果样式是“-image”样式,则必须将其扩展为包含 url() 语法。

标签: php css wordpress


【解决方案1】:

引用https://codex.wordpress.org/Theme_Customization_API#Sample_Theme_Customization_Class ...

使用像这样的 generate_css 函数扩展主题自定义类:

/**
 * This will generate a line of CSS for use in header output. If the setting
 * ($mod_name) has no defined value, the CSS will not be output.
 * 
 * @uses get_theme_mod()
 * @param string $selector CSS selector
 * @param string $style The name of the CSS *property* to modify
 * @param string $mod_name The name of the 'theme_mod' option to fetch
 * @param string $prefix Optional. Anything that needs to be output before the CSS property
 * @param string $postfix Optional. Anything that needs to be output after the CSS property
 * @param bool $echo Optional. Whether to print directly to the page (default: true).
 * @return string Returns a single line of CSS with selectors and a property.
 * @since MyTheme 1.0
 */
public static function generate_css( $selector, $style, $mod_name, $prefix='', $postfix='', $echo=true ) {
  $return = '';
  $mod = get_theme_mod($mod_name);


  // fix the issue here:
  if ($style=='background-image' && !empty($mod)) {
    $mod = 'url("'.$mod.'")';
  }


  if ( ! empty( $mod ) ) {
     $return = sprintf('%s { %s:%s; }',
        $selector,
        $style,
        $prefix.$mod.$postfix
     );
     if ( $echo ) {
        echo $return;
     }
  }
  return $return;
}

【讨论】:

  • 这是个好消息!您应该向此代码所在的任何存储库提交错误修复 - 您也应该获得荣誉;)
  • 我从您引用的页面中获取了代码并添加了背景图片,但至少如果其他人遇到同样的问题,他们应该能够轻松找到这篇文章;)
猜你喜欢
  • 2017-10-06
  • 2017-04-07
  • 2012-07-05
  • 2023-04-04
  • 2013-10-01
  • 1970-01-01
  • 2019-03-24
  • 2012-01-01
  • 2020-10-05
相关资源
最近更新 更多