Roots Discourse

Custom function works in sage 9 but not in sage 10

Hi Guys,
Im new to sage and i spent a lot of hours looking for a solution here, but in vain.
I hope someone can help:

In sage 9 i used this function display a featured image:

public static function featuredImage()
    {
        if (has_post_thumbnail()) {
            $img = the_post_thumbnail('medium', array('class' => 'img-fluid'));
        } else {
            $img = '<img class="img-fluid" src="' . \App\asset_path("images/image-default.png") . '" alt="" />';
        }

        return $img;
    }

I call it like this:

  • {!! $thumbnail !!} in an ACF Block and in content-single.blade.php

In sage 10, it didn’t work:

  • \App\asset_path doesn’t work, undefined
  • if (has_post_thumbnail()) return false all the time.

Where are you using this function?

has_post_thumbnail() require the global $post if you aren’t passing an ID to it, so it sounds like you’re calling it in a context where the global $post isn’t available. Personally I don’t like relying on the global $post ever–I pass IDs, etc, whenever I want something so that I know exactly what is being used.

\App\asset_path() is undefined because Sage 10 no longer uses that function. I would recommend using \Roots\asset() instead. This will return an Asset from which you can get a URL (as well as a number of other useful things).

Thank you for your reply.
The Path works.
Any suggestion for the has_post_thumbnail() ?

Where are you using this function?

In App\View\Composers\App.php

How are you calling it?

I’d recommend refactoring it to take an ID/post argument, and then passing that argument when you call it, i.e.

public static function featuredImage($id)
    {
        if (has_post_thumbnail($id)) {
            $img = get_post_thumbnail($id, 'medium', array('class' => 'img-fluid'));
        } else {
            $img = '<img class="img-fluid" src="' . \Roots\asset("images/image-default.png")->url . '" alt="" />';
        }

        return $img;
    }

Thank you, but how can i call it ? like this. ?

{{ featuredImage(ID) }}

This topic was automatically closed after 42 days. New replies are no longer allowed.