0

I have created an admin options page (using the Redux Theme Framework), in which the admin can customize the website's appearance (text color, background color, background repeat options, etc.. ).

Let's suppose i want to give my user the possibility of setting a custom background for a section. Admin-side, i have a media uploader form (unique id: my_div_background_url).

In the frontend, I can retrieve this option and then echo it like this:

<?php 
$options = get_option('my_theme');
$section_background_url = $options['div_background_url'];

echo '<section style="background-image: url(\'' . $section_background_url . '\');"></section>';
?>

My question is: is this the right and best way to do this? Wouldn't it be better if all of my options were saved in a css file whenever the admin changes them, and then having this file included in my website? Or are there others methods?

  • From my understanding you can't dynamically create css files, or youd have to hand write it with php, or enque a script with php that would be dynamically generated and then the script would change the css elements according to your php options variable. From my understanding thought I THINK, could be wrong but WP just passes in inline styles on elements effect by back end manipulation. – Vigs Jul 17 '13 at 20:57
2

By default, options are auto-loaded. So all options with autoload: yes will be fetched very early. Your option will not need an additional query.

Also, database access is often faster and more reliable than file access. The options table is also usually included in database backups, and it can be exported in multiple formats. So stick with options.

What you should do: escape the URL. It might have been compromised, so …

if ( ! empty ( $options['div_background_url'] )
{

    $section_background_url = esc_url( $options['div_background_url'] );

    echo "<section style='background-image: url($section_background_url);'></section>";
}

You could move the custom styles to one style element in the head element.

  • Thank you, Toscho! This has been bothering me for a while. I have just found and read this article, which, albeit being two years old, says that loading stuff into the style tag is the best ("least worse" rather) way of doing it. I'm still afraid using this method consistently (many options for each page) could have a huge impact on performances. I'll put a mockup site filled with dynamic styles and see if i can notice drops in performance - eeeh im going off-topic here. Thank you again, peace! – user35448 Jul 17 '13 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy