This snippet fetches SVG file content from a remote URL using the WordPress HTTP API. It safely retrieves and returns the SVG markup for inline usage in themes or plugins while handling request errors properly.
/**
* Retrieve SVG content from a remote URL.
*
* This helper function fetches SVG markup using the
* WordPress HTTP API and returns the SVG content
* for inline usage in themes or plugins.
*
*/
function sj_get_svg_content_from_url( $svg_url ) {
// Fetch SVG content from the provided URL.
$response = wp_remote_get( $svg_url );
// Check for request errors.
if ( is_wp_error( $response ) ) {
return 'Unable to retrieve SVG content: ' . $response->get_error_message();
}
// Retrieve the response body.
$svg_content = wp_remote_retrieve_body( $response );
// Return SVG content if available.
if ( ! empty( $svg_content ) ) {
return $svg_content;
}
return '';
}
