Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CSS to Php Wordpress plugin

I wrote a simple plugin which sets some css code using wp_options. It all looks similar like this:

add_action('init','easy_style');

function easy_style()
{
    ?>
    <style>
    #header a {
        color: <?php echo get_option('topcolor'); ?>;
        font-size: <?php echo get_option('topsize'); ?>px;
        <?php
            if (get_option('topstyle') == "bold")
            { echo "font-weight: bold;"; echo "font-style: normal;"; }
            elseif (get_option('topstyle') == "italic")
            { echo "font-style: italic;"; echo "font-weight: normal;"; }
            elseif (get_option('topstyle') == "bolditalic")
            { echo "font-weight: bold;"; echo "font-style: italic;"; }
            else { echo "font-weight: normal;"; echo "font-style: normal;"; }
        ?>;
    }

    </style>
    <?php
}

Now this works, but if I activate my "Contact Form 7" plugin, the contact form 7 doesn't work anymore. It can't send any mails. So I think what I do is wrong. If I remove this piece of code, the contact form works again...

I think I do it wrong because the css needs to be loaded in the header, no? So what I thought I would do as a test is put the same code in the header. However then some other css (i don't know where) overwrites these, so this also doesn't work.

I think there are some wp functions to add css code to the header but I don't know how exacly.

Any ideas?

Thanks

like image 619
WtFudgE Avatar asked Jun 05 '12 12:06

WtFudgE


People also ask

How can we edit HTML CSS and php file in WordPress?

Step 4: Edit Your Files Once you're logged in, you have access to your WordPress source files and can make HTML, CSS, PHP, and JS edits as you see fit. Simply right-click on any file and select View/Edit: When you've made your changes (again, be careful not to white screen your website), you can save the file.

How do you call CSS styles in WordPress?

Open up a text editor, create a new text file, save it as “custom. css” and upload it into a css folder in your active WordPress theme's folder (i.e. /wp-content/themes/theme/css/) via FTP. Download the functions. php file in your active WordPress theme's folder (i.e. /wp-content/themes/theme/) via FTP.


1 Answers

A safe way to add CSS to your plugin is to use wp_enqueue_style.

/**
 * Register with hook 'wp_enqueue_scripts', which can be used for front end CSS and JavaScript
 */
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );

/**
 * Enqueue plugin style-file
 */
function prefix_add_my_stylesheet() {
    // Respects SSL, Style.css is relative to the current file
    wp_register_style( 'prefix-style', plugins_url('style.css', __FILE__) );
    wp_enqueue_style( 'prefix-style' );
}

Reference.

like image 87
MrCode Avatar answered Sep 20 '22 17:09

MrCode