How to show featured image (medium sized) relative URL (relative to the website root)?
I need something like this: uploads/214/07/image-600x400.png
I tried with this:
if ( has_post_thumbnail()) {
$medium_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium');
echo $medium_image_url[0];
}
It works fine, I get path of medium sized featured image, but with domain name too, and I need it without domain name.
Also I tried like this:
global $wpdb;
$the_thumbnail_id = get_post_thumbnail_id($post->ID);
$the_thumbnail_name = $wpdb->get_var( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$the_thumbnail_id' AND meta_key = '_wp_attached_file'" );
//
echo $the_thumbnail_name;
This works fine, I get just relative path, but “full” sized featured image path, and I need “medium” sized featured image path.
Can anyone help me, maybe redesign (adding some parameter for “medium” size) of second function, or some new approach?
2 Answers
You’re on the right track with your first snippet – from there it’s easy to remove parts of the url: check what WP has stored as the site root, then use php’s string functions to snip that part out of your image url.
// inside the post loop, in a template file
if ( has_post_thumbnail()) {
$medium_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium');
$domain = get_site_url(); // returns something like http://domain.com
$relative_url = str_replace( $domain, '', $medium_image_url[0] );
echo $relative_url;
}
If you wanted this to exist as a reusable function:
// functions.php
function get_relative_thumb( $size ) {
global $post;
if ( has_post_thumbnail()) {
$absolute_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
$domain = get_site_url(); // returns something like http://domain.com
$relative_url = str_replace( $domain, '', $absolute_url[0] );
return $relative_url;
}
}
// in a template file
<?php
while (have_posts) : the_post();
// ... post loop content before the thumbnail
echo get_relative_thumb( 'medium' );
// ... post loop content after the thumbnail
endwhile;
?>
(Note – the result from this will likely still include the ‘wp-content/’ part of the path; if you need to remove that so it just starts at ‘upload’, just append ‘wp-content’ to the $domain variable before you run str_replace. (If this is intended for general release, you should use wordpress’ built-in functions to get the path programatically, in case someone isn’t using the typical ‘wp-content’ directory structure.)