10 Sep, 2009
Anchor Links in WordPress Posts – another shortcode solution
Posted by: Jennifer In: WordPress|WordPress Hacks
I was recently asked by a client how they could easily add anchor links within a particularly long post they had made in WordPress. (Ie. a list of links at the top of the page that would jump the user down to the appropriate section where they needed to be.) I thought about maybe explaining to them to switch over the HTML tab and writing the HTML for the anchor links, but that step alone can sometimes really freak some clients out. So I came up with a solution to the problem using shortcodes and using the "build link" button already in the WordPress edit post box.
So the first step is to create the code so the shortcode will work. If you don't already have a functions.php file in your template directory, make a new file, name it "functions.php" and add the following code (surrounded by <?php and ?>). If you do already have a functions.php file, add the following code within those php tags:
function anchorlink($atts) {
extract(shortcode_atts(array(
"id" => ''
), $atts));
return '<a name="'.$id.'"></a>';
}
add_shortcode('anchor', 'anchorlink');
Then, in your post. In front of the location you want to be able to create a link to add the following:
[anchor id="unique_id_here"]
So for example.. If your post is a "Q/A" type page, down where you have the full question and answer, add that shortcode:
[anchor id="elephantquestion"]Q: What do elephants eat?
A: Elephants eat mainly grass, leaves, bark and twigs. Sometimes they will also eat fruit and seeds.
Then at the top – where you probably have a list of all the questions on the page like this:
What do elephants eat?
What do giraffes eat?
etc.
(In this example) highlight the "What do elephants eat" text, click the LINK button in the edit post area – remove the "http://" that automatically is included in the link field that pops up and instead, add a pound symbol # and then the id you used:
I know this isn't a huge leap from simply writing the HTML that does this. But I've found that some clients don't understand (and don't want to understand) HTML. This IS actually simpler for them. Especially when you might run into the scenario of someone forgetting to close the anchor tag with a </a> – and suddenly the whole page is acting weird… I also think it's probably helpful to SEE the ID right there in plain text in the post – so that when you're making the links at the top, you can quickly see what the ID is that you need to link to.