Monday 28 April 2014

WP: Redirect back to custom page outside of wp directory after comment

Finally added product reviews for A-Rada.com. Used existing WP installation and it's comment system to show reviews on product page (will cover the topic on showing WP content on custom pages outside of it's default directory in following posts).
The problem rose with the default WP "after comment" redirect. By default after user posts it's valuable review he is redirected to default page view (say a-rada.com/blog/?page_id=32), but what we wanted is to redirect him back to appropriate product page.
With an info from wonderful Wordpress.org Support pages and with the simple code in functions.php the desired behavior was achieved.
add_filter( 'comment_post_redirect', 'my_comment_post_redirect' );
function my_comment_post_redirect( $location ){
 if (preg_match("/page_id=([0-9]*)/", $location, $match)) {
  $pageID = $match[1] + 0;
  $page_title = get_the_title( $pageID ); 

  return "http://" . $_SERVER['HTTP_HOST'] . "/product.php?" . $page_title . "#reviews";
 }
 return $location;
}
As you may see, all pages are bound to concrete products, while all posts are actually blog posts, but as I said that's another story (short one) :)