[SOLVED]How to assign an image programmatically in...
# help-with-umbraco
m
Just wondering how to assign an image programmatically. We have one page node which shows news articles via a ContentFinder but want to change the opengraph image dynamically so that it is the assigned news image rather than the opengraph image of the page node which would be the same for every news article. Something along the lines of the following, the title and descriptions work fine but you can't assign to IPublishedContent
Copy code
cs
    Model.Value<SiteBuilderSEOMeta>("titleAndDescription").Title = strTitle;
    Model.Value<SiteBuilderSEOMeta>("titleAndDescription").Description = theArticle.Value<String>("metaDescription");
    IPublishedContent newsOpenGraphImage = null;
    if (theArticle.Value<IPublishedContent>("newsImage") != null)
    {
        newsOpenGraphImage = theArticle.Value<IPublishedContent>("newsImage");
    }
    <div>image: @newsOpenGraphImage.ToString()</div>
//does not work
    Model.Value<IPublishedContent>("openGraphImage") = newsOpenGraphImage;
Is this possible? I found this page: https://docs.umbraco.com/umbraco-cms/v/10.latest-lts/fundamentals/backoffice/property-editors/built-in-umbraco-property-editors/media-picker-3#add-values-programmatically but to tell the truth I don't know how to implement this with what I have
j
IF newsOpenGraphImage is an IPublishedContent then you can't just do a .ToString(), instead it has a url property you would be able to use - newsOpenGraphImage.Url() - to get the url.
m
Sorry - the ToString was just to debug on the page. I have also tried the following but can't seem to assign a value to the media item on the fly
Copy code
cs
 IPublishedContent newsOpenGraphImage = null;
    if (theArticle.Value<IPublishedContent>("newsImage") != null)
    {
        newsOpenGraphImage = theArticle.Value<IPublishedContent>("newsImage");
    }
    IPublishedContent nodeOpengGraphImage = Model.Value<IPublishedContent>("openGraphImage");
    nodeOpengGraphImage = newsOpenGraphImage;
I have reworked the code so I no longer need to try to do this but thanks for your help
m
m
Thanks, that was the code I had already found and couldn't figure out how to implement in this situation. Not to worry - I have rewritten the news article template to overwrite the SEO/Opengraph section of the header altogether so I'm just getting the news image URL and sticking it into the HTML directly rather than trying to reassign the Opengraph image Media. But thanks
2 Views