如何将附加的css保存在css文件中并将其排队

时间:2020-10-06 作者:WeDevelop

外观->;自定义有一个附加CSS的选项,我们可以在其中添加CSS并保存它。我正在尝试将此CSS保存到一个文件中,而不是保存到数据库中并将其排队。我已成功将CSS文件排入队列,但无法动态创建和更新它。有什么提示吗?此代码中有什么错误?

add_action(\'customize_register\', \'theme_footer_customizer\');
function theme_footer_customizer($wp_customize){
 //adding section in wordpress customizer   
$wp_customize->add_section(\'custom_css\', array(
  \'title\'          => \'New Additional CSS\'
 ));
$wp_customize->add_control(\'text_setting\', array(
 \'label\'   => \'Footer Text Here\',
  \'section\' => \'custom_css\',
 \'type\'    => \'textarea\',
));




// Get upload directory
    $upload_dir = wp_get_upload_dir();

    // Create style file path
    $style_file_path = sprintf( \'%1$s/css\', untrailingslashit( $upload_dir[\'basedir\'] ) );

    // Create directories if they do not exist
    if( ! file_exists( $style_file_path ) ) {
        wp_mkdir_p( $style_file_path );
    }

    // Sanitize contents ( probably needs to be sanitized better, maybe with a CSS specific library )
    $contents = wp_filter_nohtml_kses( wp_strip_all_tags( $_POST[\'custom_css\'] ) );

    // Replace the contents of the file with the new saved contents.
    $style_file = $style_file_path . \'/my.css\';
    file_put_contents( $style_file, $contents );

    // Redirect back to page with $_GET successes and errors
    wp_safe_redirect( add_query_arg( array(
        \'success\' => true,
    ), wp_get_referer() ) );
    exit();
}

1 个回复
SO网友:WeDevelop
add_action(\'customize_register\', \'theme_footer_customizer\');
function theme_footer_customizer($wp_customize){

// Get upload directory
    $upload_dir = wp_get_upload_dir();

    // Create style file path
    $style_file_path = sprintf( \'%1$s/css\', untrailingslashit( $upload_dir[\'basedir\'] ) );

    // Create directories if they do not exist
    if( ! file_exists( $style_file_path ) ) {
        wp_mkdir_p( $style_file_path );
    }

    // Sanitize contents ( probably needs to be sanitized better, maybe with a CSS specific library )
    $contents = wp_filter_nohtml_kses( wp_strip_all_tags( wp_get_custom_css() ) );

    // Replace the contents of the file with the new saved contents.
    $style_file = $style_file_path . \'/my.css\';
    file_put_contents( $style_file, $contents );

}
remove_action( \'wp_head\', \'wp_custom_css_cb\', 101 );
// /* How to Enqueues the external CSS file */
add_action( \'wp_enqueue_scripts\', \'my_external_styles\' );
function my_external_styles() {
    $upload_dir = wp_get_upload_dir();
    wp_register_style( \'my-css\', sprintf( \'%1$s/css\', untrailingslashit( $upload_dir[\'baseurl\'] ) )  .\'/my.css\' );
    wp_enqueue_style( \'my-css\' );
}

相关推荐