Skip to content
Advertisement

wordpress plugin unexpected characters

I have enqueued a php file which contains CSS. Everything works except wordpress is throwing a fit when I activate the plugin.

The plugin generated 1230 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

Here is what I have above my CSS in my php file. <?php // We'll be outputting CSS header('Content-type: text/css'); ?>

It seems WordPress is not expecting the CSS inside the PHP file. But it does work. I’ve read in other places to just add the header content-type text/css and everything should be fine. But WordPress doesn’t like this. Can someone help?

Advertisement

Answer

The problem is that we want to write some style code into the frontend but WordPress was complaining that the headers had already been sent.

This means that something had echoed characters before WordPress had got round to setting up the headers. It turned out that the problem was sending some CSS too early.

We want this CSS to be in the <head>and WordPress provides us with a way of doing that with one of its action hooks, wp_head.

What the plugin needs to do is ask WP to add a style element with its attendant styling into the head element at the appropriate time. This is achieved by adding the action like this:

function pluginprefix_hook_css() {
    ?>
        <style>
          all the style we want to add here
        </style>
    <?php
}
add_action('wp_head', 'pluginprefix_hook_css');

Note: I have added ‘pluginprefix’ to the name of the function, and in fact you can call the function what you like, but it is advisable to have a unique prefix for your own plugin so that it cannot clash with any other name used either by WordPress itself or by another plugin.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement