Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the medium size post thumbnail url in wordpress?

What I figured out so far:

I have a query like this:

$categories=get_category_by_slug('my_category_slug')
$posts_array = get_posts( array('category'=>$categories->cat_ID, 'numberposts' => -1 ));
foreach($posts_array as $post_array){
    $queried_post = get_post($post_array->ID);
    //I can get the source file link this way: wp_get_attachment_url( get_post_thumbnail_id($queried_post->ID))
}

But the source file is just to big. Functions like the_post_thumbnail( medium ) won't work for me because it's not just url. It's an url with image tag wrapper etc. So is there a way just to get the link to the medium (or small) size file?

It's also possible to set the post thumbnail size in the functions.php after the line with the theme support and post-thumbnail:

add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 300, 300 );

I didn't try that but I don't want to set the size of all thumbnails.

like image 303
user2718671 Avatar asked Dec 02 '22 19:12

user2718671


1 Answers

Use wp_get_attachment_image_src(get_post_thumbnail_id($post_array->ID), 'medium').

This will return you an array with URL, width, height and cropping mode of this image.

EDIT: Updating to add the full code:

$categories = get_category_by_slug('my_category_slug');
$posts_array = get_posts( array('category' => $categories->term_id, 'numberposts' => -1 ));
foreach($posts_array as $post_array){
    if( has_post_thumbnail($post_array->ID) ) {
        $image_arr = wp_get_attachment_image_src(get_post_thumbnail_id($post_array->ID), 'medium');
        $image_url = $image_arr[0]; // $image_url is your URL.
    }
}
like image 135
Marin Atanasov Avatar answered Dec 26 '22 16:12

Marin Atanasov