Home / functions.php / Replace keywords in the_content and the_excerpt
  • How to Replace keywords in the_content and the_excerpt


    This is an updated version of the post from a few days ago (Link keywords or replace text in all blog posts) overall this is a better solution if you have a large list of keywords. Adding this PHP snippet to the functions.php of your wordpress theme will allow you to replace keywords within the_content and the_excerpt using an associative array.

    ( click code to copy )

    wordpress snippet : PHP

    function replace_text_wps($text){
    	$replace = array(
    		'wordpress' => '<a href="#">wordpress</a>',
    		'excerpt' => '<a href="#">excerpt</a>',
    		'function' => '<a href="#">function</a>'
    	$text = str_replace(array_keys($replace), $replace, $text);
    	return $text;
    add_filter('the_content', 'replace_text_wps');
    add_filter('the_excerpt', 'replace_text_wps');

    ( WordPress codex functions, hooks, in this snippet. )

    the_content, the_excerpt, add_filter, _e, _ex, wp,
  • If the word already is in a link, it will be some problems. My best, and simplest, solution for that is to replace eg. ‘ wordpress ‘ so that every appearence of wordpress with spaces on each side will be replaces.

    • Hi Slowmove, this is true and is something people should take into consideration when using this snippet. Thanks for the suggestion this would work great for some instances. I may have to post an updated version in the future.

  • You have to be careful of this if you intend to use those keywords on an image caption, as it seems to break the caption. That’s too much of a drawback for me to use on common keyword, but otherwise this is really great. I’ll certainly find a use for this. Thanks!

    • Hi Sean, yes this is true it will replace any text, but I’m glad you like the snippet. I’m sure that I will update it in the future to be a little more practical.

  • Pingback: Kako automatski zameniti izraze | WPSavetnik()

  • Pingback: The Best way to replace words in your posts # WordPress Tricks & Tips()

  • Pingback: WordPress Arena: A Blog for WordPress Developers, Designers and Blogger()