仅当存在修改时才使用wp_add_inline_style添加样式wp_add_inline_style

时间:2015-11-26 作者:Nastya

我正在构建一个主题,允许用户通过Customizer对其WP站点进行修改。我使用wp\\u add\\u inline\\u样式根据用户输入输出css更改。现在,无论主题是否有修改,都会将内联样式添加到头部。我想能够检查是否存在修改,只有这样才能将内联样式添加到头部。

下面是代码示例:

<?php

function mytheme_custom_styles() {

//typography setting for hero text
$onepageps_site_title_font = get_theme_mod(\'sitetitle_typography\');
$onepageps_site_title_weight = get_theme_mod(\'sitetitle_weight\');
$onepageps_site_title_style = get_theme_mod(\'sitetitle_style\');

$custom_css = "
.site-title {
        font-family:{$onepageps_site_title_font};
        font-weight:{$onepageps_site_title_weight};
        font-style:{$onepageps_site_title_style};
    }
";

wp_add_inline_style( \'theme-specific\', $custom_css );
}
add_action( \'wp_enqueue_scripts\', \'mytheme_custom_styles\' );

?>

1 个回复
最合适的回答,由SO网友:Capiedge 整理而成

请尝试以下方法:

function mytheme_custom_styles() {

    // Initialize the variable
    $custom_css = \'\';

    // check if it\'s empty
    if( \'\' != get_theme_mod(\'sitetitle_typography\') ) {
        $custom_css .= \'font-family: \' . get_theme_mod(\'sitetitle_typography\') . \';\';
    }
    // check if it\'s empty
    if( \'\' != get_theme_mod(\'sitetitle_weight\') ) {
        $custom_css .= \'font-weight: \' . get_theme_mod(\'sitetitle_weight\') . \';\';
    }
    // check if it\'s empty
    if( \'\' != get_theme_mod(\'sitetitle_style\' ) ) {
        $custom_css .= \'font-style: \' . get_theme_mod(\'sitetitle_style\') . \';\'; 
    }
    // if variable $custom_css has changed, then add the changes and execute wp_add_inline_style
    if( \'\' != $custom_css ) {
        $custom_css = \'.site-title {\' . $custom_css . \'}\';
        wp_add_inline_style( \'theme-specific\', $custom_css );
    }

}

add_action( \'wp_enqueue_scripts\', \'mytheme_custom_styles\' );
请注意,“特定于主题的”css样式表必须在主题代码的某个点排队。

如果对你有帮助,请告诉我!

相关推荐

Admin Theme customization

我遵循wordpress codex网站上关于通过插件创建管理主题的说明。我激活了插件,但我的样式表没有包含在<head>.. 这是我的代码:add_action( \'admin_init\', \'kd_plugin_admin_init\' ); add_action( \'admin_menu\', \'kd_plugin_admin_menu\' ); function kd_plugin_admin_init() { /* Register