Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to setup a function in functions.php that removes an image from the post_content on save. Everything works up until the time I'm trying to save the content, the page just hangs and I get a '500 Internal Server' error.

function remove_post_image( $post_ID ){

  // get the post
  $the_post = get_post($post_ID);

  // get the content of the post
  $post_content = $the_post->post_content;

  // replace any images
  $content = preg_replace("/<img[^>]+\>/i", "", $post_content);

  // save the post
  $my_post = array();
  $my_post['ID'] = $post_ID;
  $my_post['post_content'] = $content;

  // Update the post into the database
  wp_update_post( $my_post );   

  return $post_ID;
}
add_action('save_post', 'remove_post_image');

I fear I'm missing something very basic. Can anyone spot something I'm doing wrong?


edit

Already I see how silly this was setup. I'm having success with the following, but still would like to know if this is the best way? I'm using content_save_pre action...

function remove_post_image( $content ){

  // replace any images
  $content = preg_replace("/<img[^>]+\>/i", "", $content);

  return $content;
}
add_action('content_save_pre', 'remove_post_image');
share|improve this question

2 Answers 2

up vote 3 down vote accepted

content_save_pre would be a much better hook for striping the images and as for setting post thumbnail as post Meta you can use save_post since the first hook gets fired before post Id is set and you need that for update_post_meta.

share|improve this answer

Your function calls wp_update_post(), which calls wp_insert_post() which runs save_post action, which fires guess what? Your function.

It would be better to use something like wp_insert_post_data which is meant to filter data, rather than save_post action that is meant to merely indicate that data was already processed.

share|improve this answer
    
Haha, ok so the internal server error was from the endless functions calling eachother. Going to look at wp_insert_post_data -- thanks! –  jyoseph Jul 2 '11 at 19:35
    
Found a good solution using content_save_pre... But will I run into the same issue if I want to use update_post_meta inside that function? My end goal is I want to remove the image from the content and then use update_post_meta to set a featured image. –  jyoseph Jul 2 '11 at 19:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.