Develop

WordPress: Page Anchors as Easy Shortcodes for Clients

Background

Page anchors can be great for single page sites, or sites with long content that need to be navigable. However, you may not want you client digging around in the text view of their WordPress editor…I’m sure they don’t want to be in there either!

Anchor

fig 1.0 anchor

Setup

We are going to create a simple page anchor element that clients can add via shortcode. In addition, this anchor will be able to accommodate sites with fixed headers (like mobile and responsive sites) by adding padding based on the height of the fixed element.

Part I

Let’s create the shortcode that sets up the anchor element. Paste the following into your theme’s functions.php file, or into your functionality plugin if you’re using one.

function revconcept_anchor($atts, $content=null, $code="") {
	$return = '<div class="page-anchor" id="'.$content.'">';
	$return .= '</div>';
	return $return;
}
add_shortcode('anchor' , 'revconcept_anchor' );

The function above creates a <div> element with a class of “page-anchor”. It will also take whatever content is typed between the shortcode open/close and use it as the <div>'s ID.

Part II

We need to add a couple of lines of CSS to get this to display properly…especially if you have a fixed header or menu on your site. Add the following to you theme’s stylesheet (usually style.css):

.page-anchor {
	position: relative;
	top: -130px; /* the height of your header */
}

The CSS property of “top” will more than likely need adjusted for your site. It is creating a “cushion” of space between the anchor and the top of the browser.

Part III

Now, all we need to do to use this is to add the shortcode directly above the element you want to anchor to in the WordPress editor.

For example, if you have a heading called My Subheading and you want to anchor to it, just type the shortcode on the line above the heading like this: [anchor]myID[/anchor].

This will add the following element to the page: <div class="page-anchor" id="myID"></div>

To link to this anchor, just append #myID to the end of the page’s URL: example.com/about#myID

Conclusion

That’s it! You can of course add this shortcode to a drop-down menu in the editor, or as a note in a metabox on the page so your clients have it for easy reference. Also, note that “myID” can be any term you want…it just needs to be unique on the page.

 

{ 4 Comments }

  1. Excellent and Excellent instructions for this WordPress newbie.

  2. A big Thank You! )

  3. Pranav Sharma

    Hi Chris,

    This is awesome code and very useful.

    Thanks for coming up with such unique idea and useful code.

    Best Regards
    Pranav

    • Chris Perryman

      You are welcome. I’m glad you found it valuable!

{ Respond }

Leave a response