0

I'm new, can I use include() or get_template_part to load an SVG file uploaded as featured image directly in the HTML page?

I need to animate the svg images, but i need to easily change the image on each page.

I have tried this code but does't work, I can't find the right path, I can load only the svg images in the same folder.

    $domain = get_site_url();
    $svg_url = get_the_post_thumbnail_url(get_the_ID());
    $svg = str_replace( $domain, '', $svg_url );

    echo $svg; //only for read the url

    get_template_part($svg);
    // or
    inlcude $svg;

1 Answer 1

1

First, you don't need the URL but the server path to the file, you can get it with get_attached_file function, passing any WordPress attachment ID as a parameter. Then you need to load the contents of that SVG file directly, via file_get_contents function and echo it out to the page.

$thumbnail_id   = get_post_thumbnail_id( get_the_ID() );
$thumbnail_path = get_attached_file( $thumbnail_id );
echo file_get_contents( $thumbnail_path );
2
  • Perfect solution! can I also use it for the logo? Oct 22, 2021 at 0:17
  • @AlessioPaoletti Yes, any SVG you want to load directly if you have the attachment ID.
    – Greg36
    Oct 22, 2021 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.