We're working on this site: http://granthammond.staging.wpengine.com/ which will no longer be using tags, i need a way to strip / remove all the tag links in the post content, for example: any hyperlinks containing /tag/ need to go, in their entirety,

<a href="http://www.granthammond.com/tag/nashville-real-estate/">Tagged with: Nashville Real Estate</a>

i need to remove the whole <a> element. for all tags, across all posts.

as usual, any and all assistance is appreciated.

  • Do the links need to be removed in the database, or is it OK just to filter the output to remove the links before the post is shown to the user? – Bendoh Sep 11 '12 at 19:35
  • At this point, either is good. Ideally, removing them from the database would preferred. – joelrnorris Sep 11 '12 at 19:42

1) For existing post content, you can add a filter to the_content to remove them from the output before they are seen by a user:

function remove_tag_links( $content ) {
    return preg_replace( '#<a [^>]*\bhref=\\\?"[^"]+(?=/tag/)[^"]+\\\?"[^>]*>(.+?)</a>#si', '$1', $content );
add_filter( 'the_content', 'remove_tag_links' );

2) For new / updating content, you can add the same filter to content_save_pre to take the links out before they are saved to the database:

add_filter( 'content_save_pre', 'remove_tag_links' );

Note that my pattern expects double-quotes (and possibly backslashed-escaped double quotes, for content_save_pre) around the href attribute value, and can handle other attributes within the tag.

The filter I provided simply removes the link markup, but leaves behind the text. If you want to remove the entire tag including its text, pass an empty string '' instead of '$1' as the second parameter to preg_replace

  • I just noticed that my pattern was greedy. I have updated it to by non-greedy by adding a ? after the + quantifier in the capture group. Be sure to incorporate this change: otherwise bad things will happen if a targeted link appears in the middle of the text, followed by another one further in the content. – Bendoh Sep 11 '12 at 20:53

To your themes functions.php file, add the following:

add_filter( 'the_tags', 'remove_links' );
function remove_links($thelist) {
  return preg_replace('#<a.*?>([^<]*)</a>#i', '$1', $thelist);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.