Categories
Wordpress

Link Gallery Widget images to a Post

Something that I feel is sorely missing from WordPress is an easy way to have a bunch of random images from your media library in the sidebar which link to the Post that contains that image.

Solution 1: You can add your posts and attach an image to them, that bit is pretty easy.
The problem with this approach is that you cannot limit the number of images displayed in the sidebar without some fiddling with the theme, and even then I didn’t like how that worked. However, if that is ok with you, do the following:

To get your images to link to the post, install the WP Gallery Custom Links plugin from Four Lights Web Development, you find a few more fields at the bottom of the Edit Image page where you can put the place you really want to the image to link to. You may have thought that this would do the trick, I certainly did, however this doesn’t appear to work from the sidebar and I’ve not found a simple way to fix this with a normal sidebar gallery like Gallery Widget from Oliver Schaal not any other sidebar widget I found, but I will keep looking because this would be perfect.

To set up the sidebar gallery which does work with WP Gallery Custom Links you can install the HTML Javascript Adder plugin from Aakash Chakravarthy, drop this into your sidebar from the Appearance | Widgets section and add something like the following code:

[[gallery link="post" orderby="rand" ids="130,96,95,98,99,97,94,93,92,85,81,82,80,79,87,86,89,90,91,88"]]

Where the ids are the id of the pictures you want included.

The only problem with this approach is that you cannot limit the number of images displayed in the sidebar without some fiddling with the theme, and even then I didn’t like how that worked.

Solution 2: I ended up with this solution which works perfectly for me:

Install NextGen Gallery and also NextGen Custom Fields from Shaun Alberts

Create a new Image Custom Field in the NGG Custom fields called LinkToPost. Create a new gallery and upload your images. Set the LinkToPost field to be the URL of the Post you want to link to.

Add the NextGen Gallery Widget to your sidebar, set it how you want it.

Now edit the NextGen Gallery Widget to use your custom field as the link instead of image itself. Plugins | Editor and Select NextGen Gallery from the Select Plugin to Edit: drop down. Find the nextgen-gallery/widgets/widgets.php file and click on that.
Replace the line that says:

$out = '<a href="' . $image->imageURL . '" title="' . $description . '" ' . $thumbcode .'>';

with:

$out = '<a href="' . nggcf_get_field($image->pid, "LinkToPost") . '" title="' . $description . '" ' . $thumbcode .'>';

The case of your custom field (LinkToPost in this case) is important.

You should be done. Unless anyone knows a better way, that is what I’m using for now.

Take a look at the following sites to see the results of this:
http://tigh-na-acha.co.uk/
http://osvhazair.com