WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Add "Custom CSS" Feature to Theme (6 posts)

  1. protechig
    Member
    Posted 1 year ago #

    Hello,
    I'm in the process of developing a theme, and one feature that I like about some themes I see is the ability to add custom CSS as a setting. I know that it is also possible to do this through the theme, editor, but I want to add the ability within like a "theme options".

    How would I go about doing this?

    Thanks
    Zach Russell

  2. Marventus
    Member
    Posted 1 year ago #

    Hi!
    It is easy to insert another stylesheet in your theme, but why not create a child theme (Child_Themes) instead?

  3. protechig
    Member
    Posted 1 year ago #

    I think you have the wrong idea if what I'm asking. I know I could simply add a second style sheet and then add it through the header.php, or with a function. I want a way that you can simply add custom CSS Rules through the admin interface (think of something like a theme setting), and then it adds the code into a stylesheet from there.

  4. Andrew Bartel
    Member
    Posted 1 year ago #

    Store the paths to the style sheets users entered in the database.

    Create a file, something like, framework.php or control.php.

    Require that file on your theme's functions.php.

    In that file:
    Retrieve the style paths from the database.
    Run a loop that runs wp_enqueue_style($path) for each one.

    Make sure to sanitize your database inputs/outputs.

  5. protechig
    Member
    Posted 1 year ago #

    Ahhah makes sense. Thanks

  6. Marventus
    Member
    Posted 1 year ago #

    @protechig: Sorry for the misunderstanding, ;-)
    @Andrew: He would still need to register the custom style sheet path as an option so that the field actually appears in the theme options, right?
    Also, you would have to check whether the option is empty (or null) before including it, otherwise you will get an inclusion error.
    Something like:

    global $custom_css_url;
    function protechig_custom_css() {
        $custom_css_url = get_bloginfo('stylesheet_directory').'/fake.css/';
        wp_register_style('protechig-custom-css', $custom_css_url, '', '1.0', 'all');
        wp_enqueue_style('protechig-custom-css');
    }
    
    if ($custom_css_url) {
        add_action( 'wp_enqueue_scripts', 'protechig_custom_css' );
    }

    Of course, even though this approach works, it is rather basic so you should improve it a little (mainly, user input handlers).

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.