How do I store a custom user selected CSS template style (like wordpress visual editor)? [closed]

If you want to give users the ability to style a few HTML elements on different sections of your website, the simplest implementation is the following:

1) Create table users_styles with fields:

id (INT), user_id (INT), section_id (INT), value (VARCHAR 1000).

The value field will contain a string with the values of styles in the JSON format. Don’t forget about indexes.

2) Add constants of the style types in your PHP class, for example:

class UserStyle extends Model {

    const JOURNAL_COVER = 1;
    const FONT_NAME = 2;
    const FONT_SIZE = 3;
    const PAGE_THEME = 4;
    const PAD_THEME = 5;
    const BACKGROUND_COLOR = 6;
    // ...
}

Constants for sections:

class SiteSection extends Model {

    const MAIN = 1;
    const BLOG = 2;
    const CALENDAR = 3;
    // ...
}

3) Select types and values for the current user with the next query:

SELECT value
FROM users_styles
WHERE user_id = (int)$currentUserId
      AND section_id = (int)SiteSection::MAIN

You’ll get a string like this:

$userStyles = {"1":"sand.jpg","2":"water.jpg","3":"fire.jpg","4":"#EFEFEF","5":"Lora","6":"17px"};

After json_decode($userStyles, true); it will contain the next values:

[
    1=>'sand.jpg',
    2=>'water.jpg',
    3=>'fire.jpg',
    4=>'#EFEFEF',
    5=>'Lora',
    6=>'17px'
];

4) Insert styles as internal styles in the corresponding section template with the selected data. For example:

<style type="text/css">
body {
    font-family: "<?= $userStyles[UserStyle::FONT_NAME] ?>", serif !important;
    font-size: <?= $userStyles[UserStyle::FONT_SIZE] ?>px !important;
    background-color: #<?= $userStyles[UserStyle::BACKGROUND_COLOR] ?> !important;
}

#journal-cover {
    background-image: url("<?= $currentUserStylesFilesDirPath.$userStyles[UserStyle::JOURNAL_COVER] ?>") !important;
}

#pad-theme {
    background-image: url("<?= currentUserStylesFilesDirPath.$userStyles[UserStyle::PAD_THEME] ?>") !important;
}
<style>

This rules will rewrite all relevant rules for the styles of the body, #journal-cover and #pad-theme elements.

Leave a Comment