I have some Pinterest code to show a Pin it button on my wordpress posts but it only grabs the post thumbnail. What I want is to grab the first post content image and only grab the thumbnail if there are no images in the post!??

Have tried tons of examples but nothing works.

1 answer

danwellman 5600

You need to get the image that you want pinned with JavaScript and manually construct the pinterest button. You use jQuery? Something like this should work:

var pinterestUrl = "http://pinterest.com/pin/create/button/", //pinterest link
    pageUrl = document.URL,
    imageUrl = $(selector_for_content_images).find("img").get(0).src,
    desc = $(selector_for_brief_text_description).text(),
    complete = [pinterestUrl, "?url=", pageUrl, "&media=", imageUrl, "&description=", desc].join(""); 

$("a.pin-it-button").attr("href", complete);
Answered almost 6 years ago by danwellman
  • Thanks but wouldn't be sure how to implement that I'm afraid.. Leon Quinn almost 6 years ago
  • Probably would want to encode the URLs, otherwise you might end up with weird results or a broken url Ktash almost 6 years ago
  • Pinterest automatically encode the URLs for you. If you try to encode manually it breaks. @leon - inlcude jQuery in your page, then include the above in a script element...that's it :) If you don't want the first image on the page to be pinned, you have to do something like this... danwellman almost 6 years ago
  • A link to the site in question would help (if it's built/live) so we could see what script libraries are being used etc. The above is jQuery, but could very easily be converted to plain JavaScript if necessary danwellman almost 6 years ago
  • Sorry, don't know enough about any of this to follow instructions. I wrapped your code above in <script type="text/javascript"></script> tags and made sure jQuery was included but no change. Here's the wordpress site - http://www.reverbstudios.ie/2436/popular-ways-extend-your-wordpress-site/ Leon Quinn almost 6 years ago