How can I filter and append WordPress post/page content prior to save/publish?

I would like to filter the post and page content to append html tags to specific content prior to saving the content to the database.

For example, given a keyword phrase “Red Yoga Mats”, I would like to scan the page/post content and replace the first instance of “Red Yoga Mats” with <b>Red Yoga Mats</b> and replace the second instance with <i>Red Yoga Mats</i> and the 3rd instance with <u>Red Yoga Mats</u>.

Read More

How difficult would this be?

(The phrase “Red Yoga Mats” is arbitrary. I’d like to place this as a dynamic variable that I would pass to the filter function that does the content append)

Related posts

Leave a Reply

2 comments

  1. You could use a filter on the_content for this.

    add_filter( 'the_content', 'highlight_red_yoga_mats' );
    function highlight_red_yoga_mats($content) {
        // modify $content here
        return $content;
    }
    
  2. it would be more easy if you will make this change in moment, when post is not saved, but displayed (in this case use the_content filter hack) but if you really want to make changes when post is saved, use action hack save_post. some pseudo code:

    add_action('save_post', 'my_func');
        function my_func($post_ID) {
        // retrive content of post based on $post_ID
        // use str_replace to replace things
        // save post again
        }