Last active
April 3, 2019 13:04
-
-
Save alanef/a5016fef35298707e08e96cd701cfef3 to your computer and use it in GitHub Desktop.
Example api function call using wp functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $result = my_api_func( 'https:api....', array( 'arg1' => 'value1' ), true ); | |
| if ( is_wp_error( $result ) ) { | |
| // error | |
| } | |
| /** | |
| * @param $url | |
| * @param array $args | |
| * @param bool $json_decode | |
| * | |
| * @return array|mixed|object|string|WP_Error | |
| */ | |
| function my_api_func( $url, $args = array(), $json_decode = true ) { | |
| global $wp_version; | |
| $url = add_query_arg( | |
| $args, | |
| $url | |
| ); | |
| $http_url = $url; | |
| if ( $ssl = wp_http_supports( array( 'ssl' ) ) ) { | |
| $url = set_url_scheme( $url, 'https' ); | |
| } | |
| $http_args = array( | |
| 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ), | |
| ); | |
| $request = wp_remote_get( $url, $http_args ); | |
| if ( $ssl && is_wp_error( $request ) ) { | |
| if ( ! wp_doing_ajax() ) { | |
| trigger_error( | |
| 'An unexpected error occurred. Something may be wrong with this server’s configuration.', | |
| headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE | |
| ); | |
| } | |
| $request = wp_remote_get( $http_url, $http_args ); | |
| } | |
| if ( is_wp_error( $request ) ) { | |
| $res = new WP_Error( | |
| 'my_api_failed', | |
| 'An unexpected error occurred. Something may be wrong with this server’s configuration.', | |
| $request->get_error_message() | |
| ); | |
| } else { | |
| if ( $json_decode ) { | |
| $res = json_decode( wp_remote_retrieve_body( $request ), true ); | |
| if ( is_array( $res ) ) { | |
| // Object casting is required | |
| $res = (object) $res; | |
| } elseif ( null === $res ) { | |
| $res = new WP_Error( | |
| 'my_api_failed', | |
| 'An unexpected error occurred. Something may be wrong with this server’s configuration.', | |
| wp_remote_retrieve_body( $request ) | |
| ); | |
| } | |
| } else { | |
| // Check the response code | |
| $response_code = wp_remote_retrieve_response_code( $request ); | |
| $response_message = wp_remote_retrieve_response_message( $request ); | |
| if ( 200 != $response_code && ! empty( $response_message ) ) { | |
| return new WP_Error( $response_code, $response_message ); | |
| } elseif ( 200 != $response_code ) { | |
| return new WP_Error( $response_code, 'Unknown error occurred' ); | |
| } | |
| $res = wp_remote_retrieve_body( $request ); | |
| } | |
| if ( isset( $res->error ) ) { | |
| $res = new WP_Error( 'my_api_failed', $res->error ); | |
| } | |
| } | |
| return $res; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment