tags:

views:

24

answers:

2

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>.

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)

A: 

hi

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
    }
kkarpieszuk
@kkarpieszuk: Thanks for the suggestion and the code! I prefer to do it at save/publish time since the method will be called only a few times, vs hundreds or thousands each time the page is viewed on the public site.
Scott B
@kkarpieszuk: When you say "save post again", what would be the call to insert there? save_post($content)?
Scott B
A: 

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;
}
Adam
@Adam - can I call this when the page is loaded into the editor?
Scott B
No, that would break the purpose of having an on-the-fly filter. I guess you are looking for a function like the above poster has written.
Adam