2

I am just wrapping up my first WordPress plugin and the last thing I would like to do is take a piece of data that the plugin knows about (from wp_options table) and display it in either the header or footer of the site. It will simply be a small styled div with a 6 character code in it.

First of all, is this even possible? Does a plugin have the ability to modify a users theme?

If this is possible, what are some best practices and/or "gotcha's" to keep in mind when doing this? Obviously all themes are quite different so I want to approach this in the most generic and unobtrusive way possible.

If a plugin cannot do such a thing, I would have to imagine that it can write HTML somewhere when content is rendered, again what are best practices for handling this sort of thing?

This is my first stack exchange post without any code but since this is generic question and not specific to any particular method (yet) I feel that it is still appropriate.

Thanks!

4

Hooks are going to be your best friend here.

You can filter post content by using the the_content filter for example:

add_filter('the_content', 'wse_174099_append_to_content');

function wse_174099_append_to_content( $content ) {
    //get your data
    $custom_items = get_option( 'option_name' );

    $content .= wpautop( $custom_items );

   //always return when using a filter
    return $content;
}

You can hook into the footer of the site by hooking into the wp_footer action:

add_action('wp_footer', 'your_function');
function your_function() {
    $custom_items = get_option( 'option_name' );
    echo $custom_items;
}

You could also look at the get_header and get_footer actions. The only issue is that you can't control where the theme calls the header and footer files in - it may be a bad spot to output your code.

Hope this helps!

| improve this answer | |
  • Hey there! I have mimicked what you posted and it works in the sense that the HTML is added to the source but it doesn't show up on the page because it is outside of the container. Any thoughts on how to ensure that it targets the content of the header or footer? – Nicholas Kreidberg Jan 21 '15 at 20:20
  • 1
    The issue is where the hooks are being placed in the theme and you won't be able to control that. You could try some javascript to grab the new source and insert it into the area you want. That may get a tad hacky though. – Welcher Jan 22 '15 at 4:07
  • Sounds like I might need to add some widget functionality to the plugin then, yes? At least that way I wont have to hack in the content I want but rather allow the user to plop it into wherever their theme supports. One extra step they have to do after setup but it seems pretty among other plugins. Thanks for the input! – Nicholas Kreidberg Jan 22 '15 at 15:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.