Skip to content

Instantly share code, notes, and snippets.

@R3V1Z3
Last active December 18, 2015 10:59
Show Gist options
  • Save R3V1Z3/5772177 to your computer and use it in GitHub Desktop.
Save R3V1Z3/5772177 to your computer and use it in GitHub Desktop.
WordPress snippet to replace first occurrence of a string with another within post content, relying on the_content filter and the PHP preg_replace function. In this example, the first occurence of "WordPress" is being replaced with a link to wordpress.org. The last parameter on line 4 restricts the replacement to only the first occurrence.
<?php
function replace_content($content)
{
$content = preg_replace('/WordPress/', '<a href="http://wordpress.org/">WordPress</a>', $content, 1);
return $content;
}
add_filter('the_content','replace_content');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment