tags:

views:

23

answers:

2

I'm trying to create a function that does a text replacement on the post content when its saved (the_content).

The stub function is below, but how do I obtain a reference to the post content, then return the filtered content back to the "publish_post" routine?

However, my replacement is either not working and/or not passing the updated post_content to the publish function. The values never get replaced.

function my_function() {
    global $post;
    $the_content = $post->post_content;
    $text = " test ";
    $post->post_content = str_ireplace($text, '<b>'.$text.'</b>', $the_content  );
    return $post->post_content;
    }
add_action('publish_post', 'my_function');
A: 

Probably easier to do something like this:

function my_function($post) {
  $content = str_ireplace(" test ", '<b>'.$text.'</b>', $post->content);

  return $content;
}

Less focus was on the interior of the function, but the idea is that you pass the object to the function in the () then call the directly rather than globalizing the value. It should be more direct that way.

lodge387
Thanks Lodge. Looks great, but when I test it, the content remains the same after clicking "Update" on the post editor. I'd like to replace all instances of the word "test" with a bolded replacement...
Scott B
A: 

the passed variable here is $id. This should work:

function my_function($id) {
  $the_post = get_post($id);
  $content = str_ireplace(" test ", '<b>'.$text.'</b>', $the_post->post_content);

  return $content;
}
add_action('publish_post', 'my_function');
bhamrick
@bhamrick: does not change the post content. Where are you passing $id from? btw, like the name. I'm in bham, al
Scott B
@Scott, interesting. In my code I wanted to cover all the bases, so I used three hooks: edit_post, save_post, and publish_post. Doing a search of the WordPress (v. 3.0.1) source I don't immediately see a call for do_action('publish_post'). Maybe try save_post instead?The do_action method WordPress uses do_action('save_post', $post_ID, $post), which is where the post ID and post objects are passed.
bhamrick