1

I'm looking for a plugin or example of code that can intercept the save/publish event and verify that all external links within the post content have rel="nofollow" attributes.

Is it possible to use add_filter or add_action on the post save/publish event?

2

I would try "wp_insert_post_data" filter.

add_filter('wp_insert_post_data', 'new_content' );
function new_content($content) {    
    preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
    for ( $i = 0; $i <= sizeof($matches[0]); $i++){

        if ( !preg_match( '~nofollow~is',$matches[0][$i]) ){
            $result = trim($matches[0][$i],">");
            $result .= ' rel="nofollow">';
            $content['post_content'] = str_replace($matches[0][$i], $result, $content['post_content']);
        }

    }

    return $content;
}

Obviously needs work, just a PoC.

  • @Backie Please explain how exactly you would try to use the wp_insert_post_data filter? – EAMann Jan 21 '11 at 4:25
  • @EAMann added a little snippet of code. – Backie Jan 21 '11 at 12:35
  • @Backie, this works great, esp for a POC. Two comments: (1) How to alter the preg_match so that it skips over internal links? (2) Would there be an advantage to using "wp_insert_post_data" vs "content_save_pre"? – Scott B Jan 25 '11 at 16:41
  • backie.org/2011/01/25/… does it for external only. Only a simple change made. I wasn't able to get content_save_pre filter to work. I may have been doing it wrong tho. – Backie Jan 25 '11 at 18:38
  • @Backie: Just commented on your solution. Works great. Only suggestion would be to place the rel at the end of the attrib list vs at the beginning... – Scott B Jan 25 '11 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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