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');
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.
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');
When you mention the_content
, are you referencing the template tag or the filter hook?
the_content
as a filter hook only works on post content during database reads, not writes. The filter to use when modifying post content right before it is save to the db is content_save_pre
.
Code Example
In your plugin or theme's functions.php, add your function, using $content
as the argument. Modify the content any way you wish, and be sure to return $content
.
Then use add_filter('filter_name', 'function_name')
to run the function when the filter hook is encountered in WordPress.
function add_myself($content){
return $content." myself";
}
add_filter('content_save_pre','add_myself');
If I write a post that includes:
"To the end of posts, I like to add"
when saved to the database and displayed on the site, it will read:
"To the end of posts, I like to add myself".
Your example filter might be revised to look like this:
function my_function($content) {
$text = " test ";
return str_ireplace($text, '<b>'.$text.'</b>', $content );
}
add_filter('content_save_pre','my_function');