@@ -21,14 +21,14 @@ public function insert( array $data ): int {
2121 $ post_id = wp_insert_post ( [
2222 'post_type ' => $ this ->slug ,
2323 'post_status ' => 'publish ' ,
24- 'post_title ' => $ data ['title ' ] ?? '' ,
24+ 'post_title ' => $ this -> prepare_data ( $ data ['title ' ] ?? '' ) ,
2525 ], true );
2626
2727 if ( is_wp_error ( $ post_id ) ) {
2828 return 0 ;
2929 }
3030
31- update_post_meta ( $ post_id , self ::META_KEY , wp_json_encode ( $ data ) );
31+ update_post_meta ( $ post_id , self ::META_KEY , $ this -> prepare_data ( $ data ) );
3232
3333 return $ post_id ;
3434 }
@@ -42,11 +42,11 @@ public function update( int $id, array $data ): void {
4242 if ( isset ( $ data ['title ' ] ) ) {
4343 wp_update_post ( [
4444 'ID ' => $ id ,
45- 'post_title ' => $ data ['title ' ],
45+ 'post_title ' => $ this -> prepare_data ( $ data ['title ' ] ) ,
4646 ] );
4747 }
4848
49- update_post_meta ( $ id , self ::META_KEY , wp_json_encode ( $ data ) );
49+ update_post_meta ( $ id , self ::META_KEY , $ this -> prepare_data ( $ data ) );
5050 }
5151
5252 public function delete ( int $ id ): void {
@@ -89,4 +89,19 @@ public function all(): array {
8989
9090 return $ results ;
9191 }
92+
93+ /**
94+ * We expect $value to be unslashed, as it will either come
95+ * from Request::get_body_params() or be manually set
96+ *
97+ * Post and meta functions both expect slashed data:
98+ * @see https://developer.wordpress.org/reference/hooks/wp_insert_post_data/
99+ * @see https://developer.wordpress.org/reference/functions/update_post_meta/
100+ */
101+ protected function prepare_data ( string |array $ value ): string {
102+ if ( is_array ( $ value ) ) {
103+ $ value = wp_json_encode ( $ value );
104+ }
105+ return wp_slash ( $ value );
106+ }
92107}
0 commit comments