The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Retrieve SVG Content from External URL

Shared by Sumit Javia | Senior WordPress Developer · May 25, 2026

44 views
Back to Snippets

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 '';
}
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments

Proudly supported by