@@ -34,13 +34,64 @@ class String_Replace {
3434 public function __construct ( Plugin $ plugin ) {
3535 $ this ->plugin = $ plugin ;
3636 add_action ( 'template_redirect ' , array ( $ this , 'init ' ), 1 );
37+ add_action ( 'template_include ' , array ( $ this , 'init_debug ' ), 1 );
38+ $ types = get_post_types_by_support ( 'editor ' );
39+ foreach ( $ types as $ type ) {
40+ $ post_type = get_post_type_object ( $ type );
41+ // Check if this is a rest supported type.
42+ if ( true === $ post_type ->show_in_rest ) {
43+ // Add filter only to rest supported types.
44+ add_filter ( 'rest_prepare_ ' . $ type , array ( $ this , 'pre_filter_rest_content ' ), 10 , 3 );
45+ }
46+ }
47+ }
48+
49+ /**
50+ * Filter out local urls in an 'edit' context rest request ( i.e for Gutenburg ).
51+ *
52+ * @param \WP_REST_Response $response The post data array to save.
53+ * @param \WP_Post $post The current post.
54+ * @param \WP_REST_Request $request The request object.
55+ *
56+ * @return \WP_REST_Response
57+ */
58+ public function pre_filter_rest_content ( $ response , $ post , $ request ) {
59+ $ context = $ request ->get_param ( 'context ' );
60+ if ( 'view ' === $ context ) {
61+ $ data = $ response ->get_data ();
62+ $ data ['content ' ]['rendered ' ] = $ this ->replace_strings ( $ data ['content ' ]['rendered ' ] );
63+ $ response ->set_data ( $ data );
64+ }
65+
66+ return $ response ;
3767 }
3868
3969 /**
4070 * Init the buffer capture and set the output callback.
4171 */
4272 public function init () {
43- ob_start ( array ( $ this , 'replace_strings ' ) );
73+ if ( ! defined ( 'WP_DEBUG ' ) || false === WP_DEBUG ) {
74+ ob_start ( array ( $ this , 'replace_strings ' ) );
75+ }
76+ }
77+
78+ /**
79+ * Init the buffer capture in debug mode.
80+ *
81+ * @param string $template The template being loaded.
82+ *
83+ * @return null|string
84+ */
85+ public function init_debug ( $ template ) {
86+ if ( defined ( 'WP_DEBUG ' ) && true === WP_DEBUG ) {
87+ ob_start ();
88+ include $ template ;
89+ $ html = ob_get_clean ();
90+ echo $ this ->replace_strings ( $ html ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
91+ $ template = null ;
92+ }
93+
94+ return $ template ;
4495 }
4596
4697 /**
@@ -50,10 +101,21 @@ public function init() {
50101 *
51102 * @return bool
52103 */
53- public function string_set ( $ string ) {
104+ public static function string_set ( $ string ) {
54105 return isset ( self ::$ replacements [ $ string ] );
55106 }
56107
108+ /**
109+ * Check if a string is not set for replacement.
110+ *
111+ * @param string $string String to check.
112+ *
113+ * @return bool
114+ */
115+ public static function string_not_set ( $ string ) {
116+ return ! self ::string_set ( $ string );
117+ }
118+
57119 /**
58120 * Replace a string.
59121 *
0 commit comments