You have a blog running WordPress. You like to use the ‘more’ link for post excerpts, but you have ads running at the top of the page and the ‘more’ link puts in an anchor by default that takes the user lower on the page. How can you remove the anchor so the user goes right to the top of the page?
The beauty of maintaining a functions.php file is that for simple actions like this, you don’t need to mess around with a plugin. Readers of this blog know that I feel if you can do a simple action without a plugin, it is far more efficient. Plugins often are bloated with lots of extra code. In this example, let’s say you just want to remove the anchor from the ‘more’ link. I looked at a few plugins that do this. The problem is, 95% of the plugin code is related to managing the options and other unnecessary items. Instead, adding a simple function to your functions.php file can do the whole thing in 5 simple lines of code.
This is so simple, you don’t really even need to understand php (although it helps).
First, we need to specify to WordPress we want to do an action when it runs the_content (the function that gets the appropriate content; in this case, it is getting the excerpt and inserting the ‘more’ link).
add_action ( 'the_content' , 'strip_anchor' );
This line tells WordPress that when it runs the_content, we want to run our little function called “strip_anchor”.
Now let’s build our function.
function strip_anchor( $content ) { ... our function code will go here ... }
This defines our function “strip_anchor” and passes $content, which is WordPress’s variable for holding the post/page content.
We are going to take $content and filter it using the PHP function preg_replace which will search for a string and replace it with another string. preg_replace works like this:
preg_replace ( $look-for-this , $replace-it-with-this, $the-string-we-are-searching )
In this case, we want to search the content for the #more- anchor link and simply take it out. And that is going to provide a new value of $content. The whole thing looks like this:
$content = preg_replace("/\#more-\d+\" class=\"more-link\"/", "\" class=\"more-link\"", $content);
Then we return the new value of $content which has simply stripped the anchor link:
return $content;
Put it all together and you have:
add_action('the_content', 'strip_anchor'); function strip_anchor($content) { $content = preg_replace("/\#more-\d+\" class=\"more-link\"/", "\" class=\"more-link\"", $content); return $content; }
Put that in your functions.php file and your ‘more’ links will simply go right to the top of the page.
Enjoyed this article?
Don't miss a single post. Subscribe to our RSS feed!