2

I've written my first simple WP widget-- it all works fine, but I'd like to dress it up a bit, and add an image / logo in the widget display code.

How do I package the widget (which is just a single PHP file) with the image, and where will the image be stored in the WP site (so I can create the img tag link correctly)?

I know I could easily host the image externally and just "hotlink" to it from within my widget, but that seems a little hackish.

Thanks

2 Answers 2

4

It sounds like you'll need the plugins_url() function which generates the URL for the plugins directory and can handle any alternate configuration (such as if you moved it to the /mu-plugins/ directory, a personal favorite of mine). The Codex documentation is good, but here's a quick example.

  • Let's say you're making this in a plugin that in /wp-content/plugins/my_awesome_widget/.
  • To make the example slightly more interesting, you store all associated images in /wp-content/plugins/my_awesome_widget/assets/images/.
    • Your image is called company_logo.png.
  • In the root plugin directory is your main plugin PHP file which needs to reference the widget.

So to get the image, you'd use a snippet like this:

<?php printf(
    '<img src="%1$s" alt="{YOUR COMPANY} logo" />',
    plugins_url( '/assets/images/company_logo.png', __FILE__ )
); ?>

If all goes well, that will print out:

<img src="http://example.com/wp-content/plugins/my_awesome_widget/assets/images/company_logo.png" alt="{YOUR COMPANY} logo" />
1

You can't distribute/install a widget all by itself. There are several ways to extend WordPress:

  1. Themes
  2. Plugins
  3. Or, more rarely, Must Use Plugins

"Widget" is not an extendable feature. There is no way to drop that in directly, so the widget code has to be written into a theme or into a plugin. In your case, it sounds like the latter, so put the image in the folder with the plugin.

In other words, you need to create a plugin to load the widget and that gives you a place to put your image file, as well as any other files you might need.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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