Tag Archives: WordPress

We occasionally receive emails from our visitors with a specific question that we can refer to an article or section of a page on our website. However, with our lengthy articles, often times we find it frustrating to direct the user to a page with few lines of instructions. This is where anchor tags come in for the help. We decided to manipulate the content and add anchor tags to all our H2 tags.

Here is a feature that we thought is missing in WordPress

Add this code in your functions.php file and all your H2 tags will get an id attributes. Here we use WordPress’s built in sanitize_title_with_dashes function that’s used for creating permalinks when you type in your new post title.

// This function adds nice anchor with id attribute to our h2 tags for reference
// @link: http://www.w3.org/TR/html4/struct/links.html#h-12.2.3

function anchor_content_h2($content) {

    // Pattern that we want to match
    $pattern = '/<h2>(.*?)</h2>/';

    // now run the pattern and callback function on content
    // and process it through a function that replaces the title with an id 
    $content = preg_replace_callback($pattern, function ($matches) {
                $title = $matches[1];
                $slug = sanitize_title_with_dashes($title);
                return '<h2 id="' . $slug . '">' . $title . '</h2>';
            }, $content);
    return $content;

add_filter('the_content', 'anchor_content_h2');

And there we have our anchor tags. Now we can link to specific sections of our website like How to overwrite a CSS rule. Add some smooth scrolling if you desire, and you will have an impressive and user friendly website.

Why this feature is not a default in WordPress you ask?

Well, according to W3C Recommentatin for anchor tags, you can not have id attributes declare the same name twice in the same document. And since these elements are coming from the content editor generated by the user, there is no way to produce a valid markup if users use the same sub headings in the same post.

You wanted to start a website. You asked your more tech savvy friend for help, or just searched on Google and found some articles that all talk about using WordPress as a starting point for creating your website. But…

Do you know why they tell you to use WordPress?

Or even if this was your choice and you would like to know if you have made the right choice to build your website on WordPress read on.

Continue Reading Somebody told you to use WordPress for your website, but do you know why?