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.

In the function below, the save_content function runs, but the doReplace does not (echo

"This is the doReplace" never shows. Any ideas why?

add_action('content_save_pre', 'save_content');

 function save_content($content){
  global $post;
  $mykeyword = rseo_getKeyword($post);
  $mykeyword = preg_quote($mykeyword, '/');
  $content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $content);
 return $content;
 }

 function doReplace($matches)
 {
  echo "This is the doReplace";
  die;
  }
share|improve this question
    
You do global $post, but at the time content_save_pre runs, no $post object exists (since you are right before saving it). Could this be your problem? –  Jan Fabry Nov 4 '10 at 15:52
    
@Jan: that certainly sounds logical, but I'm able to echo $post->ID inside of save_content(). How can this be possible? –  Scott B Nov 4 '10 at 18:10
    
It appears a draft post is saved in the database, which is later overwritten by the actual post data? So I think you are getting the data of this draft post. Can you debug what rseo_getKeyword() returns there? Have you tried preg_replace_callback() with a fixed keyword? –  Jan Fabry Nov 4 '10 at 18:25
add comment

2 Answers

up vote 1 down vote accepted

Your function needs to return the data, not echo it..

function doReplace($matches) {
    return "This is the doReplace";
}

Hope that helps..

share|improve this answer
    
Indeed, in a normal regex callback you want to return the replacement string. But Scott is probably debugging, and then this code should echo the output to the screen and die, no? –  Jan Fabry Nov 4 '10 at 15:28
    
Jan is correct. I'm just debugging the code. –  Scott B Nov 4 '10 at 15:32
    
But, still... nothing gets echoed to the screen during the save_content, does it? I was under the impression it was done as an AJAX request, so trying to echo something would have no visual effect. I would think you'd be better off returning a value into your post that you could check for later. –  goldenapples Nov 4 '10 at 18:59
add comment

Shouldn't the preg_quote() call be used in an array map call? If you're feeding it something like "foo|bar" it'll get escaped as "foo\|bar", which won't match anything... Better use something like this:

// uncomment in case you're returning a string:
// $kw = explode('|', $kw);
// create a new function if php 5.3 is not an option
$regex = array_map(function($in) {
  return preg_quote($in, '/');
}, $kw);
$regex = implode('|', $regex);
share|improve this answer
add comment

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.