Skip to content
Advertisement

Return URL query into post shortcode from functions.php in WordPress

I am able to get the shortcode to return the string ‘evs’ inline in post [ when I plug that in to return ] but unable to return the post thumb url, using the same shortcode from functions.php

What am I doing wrong here:

    function thumburl_func( $atts ){
        
        $url = get_the_post_thumbnail_url('large');
//      $eva = 'evs';
        return strval($url);
    }
    add_shortcode( 'thumburl', 'thumburl_func' );

Been stuck on this for ages now – please save my week !

Advertisement

Answer

You are almost there, but you are using get_the_post_thumbnail_url incorrectly.

The size of the image you want is the second argument into the function, the first argument is the post id. Although the post id is optional, if you want to pass in the size, you need include something as the first argument.

If you are in the WordPress “loop” and the global $post is set up, you can simply pass in null e.g.

$url = get_the_post_thumbnail_url(null, 'large');

However, as this is for a shortcode, the best option is to explicitly pass in the post id – this means the shortcode will work even outside the loop (e.g. in a widget).

function thumburl_func( $atts ){
    // 1. get the post id of the current post
    $post_id = get_queried_object_id();

    // 2. pass the post is into get_the_post_thumbnail_url
    $url = get_the_post_thumbnail_url($post_id, 'large');

    return $url;
}
add_shortcode( 'thumburl', 'thumburl_func' );
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement