user1200640
user1200640

Reputation: 1087

how do I change the href link dynamically?

how do I change the href link dynamically ?

<link rel="image_src" href="" id="ShareImageID"/>

so that when someone share the web page on facebook the thumbnail shows specific image from that link tag.

I do not want to change the link for each page.

I also tried to use the og:image, it worked but I was not able to change it dynamically. I also tried this

<script>
var ShareImageIdVar = location.href.match(/\d+/);
document.getElementById('ShareImageID').href = 
        "http://www.mysite.com/Images/"+ ShareImageIdVar +".jpg";
</script>

but it is not working :( facebook is still choosing another thumbnail. a random one.

Upvotes: 0

Views: 634

Answers (2)

iambriansreed
iambriansreed

Reputation: 22241

You cannot change the Facebook image with JavaScript. When you share a link on Facebook, Facebook scrapes the page looking for images. This scrape doesn't run JavaScript.

You will need to change the image server side, possibly with PHP.

Upvotes: 1

JimmyBanks
JimmyBanks

Reputation: 4708

If you want Facebook to select the proper image when your link is posted, you need to have the proper OpenGraph image chosen in the <head> of your php file.

you can read more about open graph here https://developers.facebook.com/docs/opengraph/

Make sure to have all the necessary OG elements, for it to work properly.

Since you are asking about the image, you should have something like this:

 <head>
 <meta property="og:image" content="/images/pageimage.png" />
 </head>

To dynamically alter it, just use an echo that is specific to the php page edit/like this:

<meta property="og:image" content="<?php echo "$imageurl" ?> />

just set the variable $imageurl specifically on each php page.

Upvotes: 0

Related Questions