WordPress Attachment Page Template Code Snippets

Date: 15th November 2009 at 4:25 am | Filed under: scripts, wordpress | Author: Sam Burdge | Tags: , , , , ,

I haven't written as many WordPress tutorials as usual lately, as I have been so busy building websites and blogs, so I thought I would take the time out to share a few WordPress codes I have developed recently for attachment page templates and specifically the image attachment page template. The attachment page template is the page that displays a single image when the images link URL is set to 'Post URL'. You can set the image's link URL when inserting a single image into a post, and also when using the gallery shortcode.

The codes in this article are mostly applicable to images inserted using the gallery shortcode as they are most useful for posts or pages that have multiple image attachments. Read more about using image and file attachments.

These template codes can be added to your WordPress theme using the attachment.php and image.php files. If these template files do not exist in your theme you can create them, or WordPress will default to using single.php or index.php to show attachments by default. (See more about template hierarchy).

If you don't want to create a seperate image.php or attachment.php template you can always edit the index.php or single.php files and wrap the attachment specific codes in the is_attachment clause like so:

if(is_attachment()){
//attachment page specific code goes here
}

These php functions are loosely based on code I found in this article: Adding text links to WordPress Gallery by Michael Fields. In this article he provides code examples of how to show previous and next thumbnail links in a WP attachment page. I also made use of this previous-next keys in array function which is infinitely useful!

My first set of functions will return text links for previous image, next image and back to gallery. The functions themselves will need to be added to your theme's functions.php file before calling them in your image.php or attachment.php files. So here we go:
Read on…

15 Responses to “WordPress Attachment Page Template Code Snippets”

  • Comment by doriggidy
    Date: April 25th, 2010 at 8:08 pm

    Hi this is a great tutorial. I’m currently using nextgen gallery but want to try your gallery on my sister’s blog…so using the built in image features of WP seem to be the best solution. What you have here should be perfect for her. Great job. One question, If I wanted to have the images themselves link to the next image…how wold i do that?

  • Comment by muscle car
    Date: May 24th, 2010 at 4:29 pm

    hay that’s the cool one,but how to create thumbnail picture in random,place in sidebar or in home page header,thaks b4

  • Comment by Ted
    Date: May 27th, 2010 at 11:47 pm

    This worked perfectly for me … except, for some reason I can’t get the image captions to display. Any thoughts why they might not be coming in?

  • Comment by Shariff
    Date: July 7th, 2010 at 4:13 pm

    Wonderful Tutorial, at last I found it, I am going to try this in my blog.

    Great Going

  • Comment by Jason
    Date: July 9th, 2010 at 4:16 pm

    Thank you for this tutorial, it helped me immensely.

  • Comment by David Hobson
    Date: August 5th, 2010 at 3:59 pm

    First let me say, I am an experienced computer/internet user, however my developer side is still just an apprentice. But as a user, the second I saw white and other colored text on black background, I closed it and went on. I decided to come back and let you know because I’m sure I’m no the only one who’s done so. You might want to see what other developers think and if this technique is advisable. At least my eyes are hurting right now. Peace.

  • Comment by 2k
    Date: October 4th, 2010 at 12:27 pm

    Hi, excellent function to output the all thumbnails to attachments.php Would be amazely cool to adapting it to single.php. Is there any way to output all thumbnails the same way for single.php?

  • Comment by michelle
    Date: October 26th, 2010 at 12:56 am

    Very helpful. Thank you!

  • Comment by Clark
    Date: January 16th, 2011 at 7:38 pm

    Helpful stuff, exactly what I needed!

  • Comment by David
    Date: January 23rd, 2011 at 11:20 am

    Hi, nice tuto ! I just want to say I think the function array_navigate / prev_att_link / next_att_link could be done with one line of code ! See the wordpress function : wp_link_pages(); (http://codex.wordpress.org/Function_Reference/wp_link_pages) and to see an exemple you can look the code of the attachment.php twentyten wordpress theme.

  • Comment by David
    Date: January 23rd, 2011 at 2:15 pm

    Sorry, it’s not wp_link_pages () but previous_image_link(false) and next_image_link () with false option to insert the title : http://codex.wordpress.org/Function_Reference/previous_image_link

  • Comment by onetrek
    Date: February 27th, 2011 at 5:21 am

    This tutorial is good. But it difficult to read because of the page color. Font size if too small. As a web developer I Suggest you to make your template white color. and big font size.

  • Comment by Marirano MARINI
    Date: March 31st, 2011 at 7:44 am

    When I split an article into 2 column the first row of the second column start one line bottom.
    How can I prevent this?

    Thank you. I appreciate your job and I’ll use it when this “bug” will be take off.
    Great work!

  • Comment by surface encounters
    Date: April 7th, 2011 at 5:17 pm

    Thanks manos! Taking the two leading spaced off the end of the functions.php file worked great. Thanks!

  • Comment by Kevin
    Date: June 21st, 2011 at 8:02 pm

    Thanks for the thumbnail function! Works great!!!
    The selecting of text with your particular color scheme is hard to see though!
    Excellent work =)

Leave a Comment

WordPress attachments hack

Date: 9th June 2009 at 3:19 pm | Filed under: blog, development, scripts, wordpress | Author: Sam Burdge | Tags: , , , , , ,

While working on a WordPress site recently I came up against a problem that had never occurred to me before. The client wanted each post excerpt on the homepage to include an image which when clicked would link to the main post (permalink) itself. The built in functions of wordpress when inserting an image allow you to link to either the 'File URL' (i.e. the full size version of the image) or to the 'Post URL' which is actually an attachment page in wordpress which displays the image, but does not include the text of the actual post itself. However, without either editing the html of each post (not an option for this client) or inserting the image without a link, and then adding the permalink to the image (too long winded) there was no simple way to create the image links in the way they wanted them.

My solution to this was to create a very basic hack which would allow them to use the 'Post URL' link when inserting images, but instead of linking to the attachment page, the link would automatically be updated to link to the post's permalink itself.

Here is the basic php function that you would need to insert into your theme's functions.php file:

function lose_attachment($content){
return preg_replace('/<a(.*?)href="(.*?)\/attachment\/(.*?)"/i', '<a$1href="$2"', $content);
}

add_filter('the_excerpt', 'lose_attachment',2);

This will remove the 'attachment/name-of-image-file' part from the URL making it link to the post's permalink itself.  I hope someone out there finds this useful!

7 Responses to “WordPress attachments hack”

  • Comment by akshay
    Date: June 14th, 2009 at 3:27 pm

    really good post….tutorial is very helpful for me …thanks a lot for giving out such good tutorials

  • Comment by Alex Holsgrove
    Date: June 29th, 2009 at 8:54 am

    This was a great help. Thanks for sharing the code

  • Comment by Abeon
    Date: July 13th, 2009 at 10:26 pm

    This is a great little hack :)
    Simple but effective!

  • Comment by Nate
    Date: August 12th, 2009 at 1:21 pm

    I can’t wait to try this out.

  • Comment by Betaclick SEO Company
    Date: September 17th, 2009 at 7:32 pm

    Thanks for the code dude, i need to try this out on my wordpress blog! As im learning advanced use of it.

  • Comment by Webbando
    Date: April 12th, 2010 at 10:51 am

    Hi Sam. Thanks for your post, really useful. But I would have another thing:
    I want change permalink of attachment file from

    http://site.ext/postname/postname-post_id.html/attachment-name

    to

    http://site.ext/photos/attachment-name

    Is it possible?

    Thanks a lot for your support

  • Comment by William Lindley
    Date: March 2nd, 2011 at 1:43 am

    You might also try the AutoNav plugin, which will automatically generate thumbnails and links to child pages, to posts in a category or by slug or author, or by page/post ID:

    http://wordpress.org/extend/plugins/autonav/

Leave a Comment

Forcing a file to download using php headers

Date: 4th May 2009 at 11:57 am | Filed under: development, scripts | Author: Sam Burdge | Tags: , , ,

If you create a hyperlink to a media file that can be opened within the browser such as an mp3, mpg, jpg, pdf, etc. a single left click will open the file in the web browser instead of triggering a download. To download the file you need to right click (CTRL + click for mac) and choose 'Save File As...' from the dropdown.

If your intention is to create a link for the user to download the file rather than viewing it in their browser you can do so using a simple php script. Create a file called 'download.php' and copy in the following php:

<?php
$download_file = $_GET['file'];
$download_file_name = $_GET['name'];
$handle = fopen($download_file, "r");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$download_file_name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($download_file));
ob_clean();
flush();
readfile($download_file);
fclose($handle);
exit;
?>

You can then create your download links like so:

www.example.com/download.php?file=images/example.jpg&name=hello.jpg

The URL should include the path to the file to be downloaded, and the name you want to give the file. In the above example the file is 'images/example.jpg' but the name of the file downloaded by the user would be 'hello.jpg'

When using PHP headers it is important to note that the headers will only be executed if they are called before any text is output to the page. Any html, or php echo tags, before the headers will cause the headers to be ignored. A line break or space before the opening php tag will also prevent headers from working.

Leave a Comment

Detecting keypresses cross-browser using jquery

Date: 26th February 2009 at 8:36 pm | Filed under: development, scripts | Author: Sam Burdge | Tags: , , ,

Using keypresses as an alternate way to to navigate through websites  is a great way to make sites more accessible. For instance pressing 'p' takes the user to the previous page, while pressing 'n' takes them to the next. The benefits of using jQuery to achieve this are:

  1. Concise code
  2. Easy to implement various functions on keypress
  3. Works on IE, Firefox & Safari

DETECTING THE KEY CODE

To detect which key a user has pressed you need to set up a function that returns an ascii code each time a key is pressed. A full table of ascii codes is available here. The tricky part to this is that Mozilla and Safari define the value as charCode, while IE defines  it as keyCode. The following script is based on the 'n' key and 'p' key, it takes the links from the 'Previous' and 'Next' buttons on your site and changes page when the key is pressed. Also note that it is important to detect for both the lower-case and upper-case letter as the ascii codes will be different for each.

SOURCE

//process this function whenever a key is pressed
$(document).keypress(function (e) {
//Next
//if the keyCode or charCode is 110 (lower case n) or 78 (upper case N)
if (e.keyCode == 110 || e.charCode == 110 || e.keyCode == 78 || e.charCode == 78){
//grab the href attribute from the link with the id "next_link"
var next_link = $("a#next_link").attr("href");
//if the next link exists (i.e if it's not the last page)
if(next_link){
//go to the next page
window.location = next_link;
}
}
//Previous
//works exactly as the above example but for the 'p' and 'P' keys
if (e.keyCode == 112 || e.charCode == 112 || e.keyCode == 80 || e.charCode == 80){
var prev_link = $("a#prev_link").attr("href");
if(prev_link){
window.location = prev_link;
}
}

});

You must have the jQuery library installed on your site to run this script. For more info about jquery visit the site: http://jquery.com/

7 Responses to “Detecting keypresses cross-browser using jquery”

  • Comment by Steve Holden
    Date: June 26th, 2009 at 4:03 pm

    What happens when the page contains a form and the user types into the form inputs?

  • Comment by Sam Burdge
    Date: June 26th, 2009 at 4:27 pm

    Hi Steve
    Good question. I hadn’t tested that.
    You could always try working around this by using the focus() and blur() events for the form input to switch the keypress function on or off.

    Basic example:

    $(’input’).focus(function(){
    var keypress_active = false;
    });
    $(’input’).blur(function(){
    var keypress_active = true;
    });

  • Comment by lionel
    Date: October 8th, 2009 at 9:39 pm

    Hi, thanks for the infos, the code is working well, but is it possible to replace the windows.location by an ajax call ? thanks ?

  • Comment by lionel
    Date: October 8th, 2009 at 9:40 pm

    if yes how ? ;) thanks

  • Comment by links for 2010-03-13 | Folks Pants
    Date: April 8th, 2010 at 5:22 pm

    [...] Detecting keypresses cross-browser using jquery | Sam Burdge (tags: jquery keypress) [...]

  • Comment by Jason Cramer
    Date: March 15th, 2011 at 11:58 pm

    BRILLIANT! This was exactly what I had been looking for. Love the color scheme to your site too. Very retro DOS-ish.

  • Comment by Rachel Nabors
    Date: March 17th, 2011 at 1:49 pm

    Hello Sam! This is exactly what I am looking for for arrow-key navigation through my comics site. I need to disable it when people are typing in comment fields, though, and I just can’t seem to implement your example code for disabling above.

    Could you expand on it a bit? It would be a great help if you could!

Leave a Comment

A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute using jQuery

Date: 15th February 2009 at 4:48 pm | Filed under: development, scripts | Author: Sam Burdge | Tags: , , , , , ,

I was recently confronted with the problem of having a single html form with three different submit buttons, each button submitting the form data to a different php script. This is obviously impossible with html alone, as a form can only have one 'action' attribute, which dictates the URL of the file that the form's data is submitted to.

I searched around on the web for an easy way to implement this and found various examples. One of the best examples I found was on CoderLab's blog: Multiple submit buttons on a multiple blog which uses javascript to apply a different action attribute to the form depending on which button is pressed. Each button in the form has it's own onClick function like so:

<form name="myForm" id="myForm">
Search: <input type="text" id="wrdSearch"/>
<input type="button" name="google" id="google" value="Google" onClick="SendTo(this.id)"/>
<input type="button" name="msn" id="msn" value="MSN" onClick="SendTo(this.id)"/>
<input type="button" name="yahoo" id="yahoo" value="Yahoo" onClick="SendTo(this.id)"/>
</form>

(Visit the page to see the javascript that goes with it: http://blog.coderlab.us/2005/10/04/multiple-submit-buttons-in-a-form/)

As I already had jQuery installed on the site, and the CoderLab script would still need some modification to serve my specific purpose, I decided to see if I could find a simpler way to achieve a similar result using jQuery. The form on my site was a lot more complex, with many fields etc. So what I really needed was a script that would submit all the form data to each of the 3 php scripts depending on which submit button was clicked.

Firstly, I stripped the onClick functions out of the form and removed the name attributes from the buttons too, like so:

<form id="myForm" method="post">
Search: <input type="text" name="search"/>
<input type="button" id="button1" value="Submit to script 1" />
<input type="button" id="button2" value="Submit to script 2" />
<input type="button" id="button3" value="Submit to script 3" />
</form>

I then wrote the following jQuery script to change the form's action attribute accordingly and submit it when each button is pressed:

$(document).ready(function(){

$("#button1").click(function(){
$('form#myForm').attr({action: "script_1.php"});
$('form#myForm').submit();
});

$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});

$("#button3").click(function(){
$('form#myForm').attr({action: "script_3.php"});
$('form#myForm').submit();
});

});

The script should work on any browser that is compatible with jQuery (see here: http://docs.jquery.com/Browser_Compatibility)

For more information on installing and using jQuery visit the website: http://jquery.com/

10 Responses to “A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute using jQuery”

  • Comment by A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute using jQuery - PHP-update.co.uk
    Date: March 11th, 2009 at 1:55 pm

    [...] More here: A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute controlling j… [...]

  • Comment by Dickram
    Date: March 16th, 2009 at 6:33 pm

    You rock man. I was just looking for this and found your site. I’m using jquery too, with code igniter.
    Thank you very much!!

  • Comment by David
    Date: September 24th, 2010 at 1:04 am

    Hey, your article gives me a big help. Why using $(’form#myForm’) rather than $(’#myform’) though?? thank you very much

  • Comment by Sam Burdge
    Date: September 24th, 2010 at 1:17 am

    Hi David
    Glad it helped ;)

    there is no difference between using $(’form#myForm’) or $(’#myform’)

    i just wrote it that way as i thought it would make it clearer for the tutorial.

  • Comment by David
    Date: September 24th, 2010 at 4:25 am

    Thank you for your reply!~many thanks mate

  • Comment by Ben
    Date: October 4th, 2010 at 10:12 am

    Brilliant, cheers mate. Really helped me out of a whole

  • Comment by Ben
    Date: October 4th, 2010 at 10:13 am

    that should have said a whole world of frustration!!

    (pressed enter a little early)

  • Comment by Tom Lackey
    Date: April 27th, 2011 at 9:21 pm

    this served me well, thanks!

  • Comment by Vishal
    Date: June 10th, 2011 at 9:50 am

    Wow….great stuff… really helped a lot.. thanx buddy.

  • Comment by Mr. Serra
    Date: June 17th, 2011 at 2:57 pm

    God save the internet and people like you!
    Thank you very much!!

Leave a Comment