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
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="https://wordpress.stackexchange.com/questions/98621/%1$s" alt="{YOUR COMPANY} logo" />',
plugins_url( '/assets/images/company_logo.png', __FILE__ )
); ?>
If all goes well, that will print out:
<img src="https://example.com/wp-content/plugins/my_awesome_widget/assets/images/company_logo.png" alt="{YOUR COMPANY} logo" />