December 17, 2014

Add Link Anchors to WordPress Using a Simple Shortcode

If you have ever tried to put an ID tag on an element in your WordPress content editor, you would know that getting WordPress to retain an ID is hard to do sometimes. In most cases there is no need for an ID tag, but what do you do when you want to use an Anchor Tags ?

So, I have found that the best to use anchors is to pass a DIV with an ID using a Shortcode. An Anchor Shortcode can especially come in handy when tiring to add Anchor Tags to your WordPress Site.

Let’s create an Anchor Tag Shortcode. Paste the following into your theme’s functions.php file, or into your functionality plugin if you’re using one.

Shortcode: [nix-anchor id=”#anchor”]

Output: <div name=”anchor” class=”nix-anchor” id=”anchor”></div>

function nix_anchor( $atts ) {
   extract( shortcode_atts(
          'id' => '',
          ), $atts )
   return '<div name="'. $id .'" class="nix-anchor" id="'. $id .'"></div>';
 add_shortcode( 'nix-anchor', 'nix_anchor' );

Now, all we need to do to use this is to add the shortcode [nix-anchor id=”#anchor”] directly above the element you want to anchor to in the WordPress editor. Remember to change the “#anchor” to match the ID you want to anchor to navigate.

To link to this anchor, just append #anchor to the end of the page’s URL:

That’s it! You have the ability to make a quick anchors anywhere around your WordPress site.