@@ -23,6 +23,14 @@ function wittypen_generate_api_key()
2323 update_option ('wittypen_api_key_user_id ' , get_current_user_id ()); // Store the current user ID in the database
2424}
2525
26+ add_action ('rest_api_init ' , function () {
27+ register_rest_route ('wittypen/v1 ' , '/publish ' , array (
28+ 'methods ' => 'POST ' ,
29+ 'callback ' => 'wittypen_publish_content ' ,
30+ 'permission_callback ' => 'wittypen_authenticate_request '
31+ ));
32+ });
33+
2634add_action ('admin_menu ' , 'wittypen_create_menu ' );
2735
2836function wittypen_create_menu ()
@@ -86,23 +94,26 @@ function wittypen_display_api_key()
8694 EOT ;
8795}
8896
89- function wittypen_authenticate_request ($ result ) {
90- // Get the current REST route
91- $ route = $ _SERVER ['REQUEST_URI ' ];
97+ function wittypen_publish_content (WP_REST_Request $ request ) {
98+ $ content = $ request ->get_param ('content ' );
99+ $ title = $ request ->get_param ('title ' );
100+ $ status = $ request ->get_param ('status ' );
92101
93- // Check if the route matches plugin's namespace (replace 'wittypen/v1' with your actual namespace)
94- if ( strpos ( $ route , ' wittypen/v1 ' ) === false ) {
95- // This is not a request related to plugin, return the original result
96- return $ result ;
97- }
102+ $ post_id = wp_insert_post ( array (
103+ ' post_title ' => $ title ,
104+ ' post_content ' => $ content ,
105+ ' post_status ' => $ status ,
106+ ));
98107
99- if (!empty ($ result )) {
100- // Another authentication method is being used, return the result
101- return $ result ;
108+ if ($ post_id ) {
109+ return new WP_REST_Response (array ('success ' => true , 'post_id ' => $ post_id ), 200 );
102110 }
103111
104- // Get the Authorization header
105- $ authorization_header = isset ($ _SERVER ['HTTP_AUTHORIZATION ' ]) ? $ _SERVER ['HTTP_AUTHORIZATION ' ] : '' ;
112+ return new WP_Error ('publish_error ' , 'Failed to publish content ' , array ('status ' => 500 ));
113+ }
114+
115+ function wittypen_authenticate_request () {
116+ $ authorization_header = isset ($ _SERVER ['HTTP_AUTHORIZATION ' ]) ? $ _SERVER ['HTTP_AUTHORIZATION ' ] : '' ;
106117
107118 if (empty ($ authorization_header )) {
108119 // No Authorization header was provided, return an error
@@ -120,8 +131,5 @@ function wittypen_authenticate_request($result) {
120131 // The API key is valid, set the current user to the user associated with the API key
121132 wp_set_current_user (get_option ('wittypen_api_key_user_id ' ));
122133
123- // Return null to indicate that authentication was successful
124- return null ;
134+ return true ;
125135}
126-
127- add_filter ('rest_authentication_errors ' , 'wittypen_authenticate_request ' );
0 commit comments