class-remove-reply-to-com.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Frontend
  6. */
  7. /**
  8. * Class WPSEO_Remove_Reply_To_Com
  9. *
  10. * @since 7.0
  11. */
  12. class WPSEO_Remove_Reply_To_Com implements WPSEO_WordPress_Integration {
  13. /**
  14. * Registers the hooks necessary to handle removing ?replytocom.
  15. *
  16. * @since 7.0
  17. *
  18. * @return void
  19. */
  20. public function register_hooks() {
  21. if ( $this->clean_reply_to_com() ) {
  22. add_filter( 'comment_reply_link', array( $this, 'remove_reply_to_com' ) );
  23. add_action( 'template_redirect', array( $this, 'replytocom_redirect' ), 1 );
  24. }
  25. }
  26. /**
  27. * Removes the ?replytocom variable from the link, replacing it with a #comment-<number> anchor.
  28. *
  29. * @todo Should this function also allow for relative urls ?
  30. *
  31. * @param string $link The comment link as a string.
  32. *
  33. * @return string The modified link.
  34. */
  35. public function remove_reply_to_com( $link ) {
  36. return preg_replace( '`href=(["\'])(?:.*(?:\?|&|&#038;)replytocom=(\d+)#respond)`', 'href=$1#comment-$2', $link );
  37. }
  38. /**
  39. * Redirects out the ?replytocom variables.
  40. *
  41. * @since 1.4.13
  42. * @return boolean True when redirect has been done.
  43. */
  44. public function replytocom_redirect() {
  45. if ( isset( $_GET['replytocom'] ) && is_singular() ) {
  46. $url = get_permalink( $GLOBALS['post']->ID );
  47. $hash = sanitize_text_field( $_GET['replytocom'] );
  48. $query_string = remove_query_arg( 'replytocom', sanitize_text_field( $_SERVER['QUERY_STRING'] ) );
  49. if ( ! empty( $query_string ) ) {
  50. $url .= '?' . $query_string;
  51. }
  52. $url .= '#comment-' . $hash;
  53. $front = WPSEO_Frontend::get_instance();
  54. $front->redirect( $url, 301 );
  55. return true;
  56. }
  57. return false;
  58. }
  59. /**
  60. * Checks whether we can allow the feature that removes ?replytocom query parameters.
  61. *
  62. * @return bool True to remove, false not to remove.
  63. */
  64. private function clean_reply_to_com() {
  65. /**
  66. * Filter: 'wpseo_remove_reply_to_com' - Allow disabling the feature that removes ?replytocom query parameters.
  67. *
  68. * @param bool $return True to remove, false not to remove.
  69. */
  70. return (bool) apply_filters( 'wpseo_remove_reply_to_com', true );
  71. }
  72. }