Search code examples
jquerysharemeta

How to change the meta tag images when sharing a post in social media depending on the url with jquery?


I need to find a way to change the meta tag content images in the tag of the HTML page depending if the url matches a certain word.

I was able to change the meta tag content images to share the articles on twitter, facebook, linkedln, etc... however it is always the same picture.

My customer wants to change the image depending of the post to share. I will need to create function with the different params to check if the url matches a certain string it changes the content in the meta tags dynamically. How can I do that with jquery? or any other suggestions are welcome!

    var imgSrc = $('property[og="image:url"]').attr("content");
    var currentUrl = window.location.href ;


    if(currentUrl.toLowerCase().indexOf('certain string in url') >= 0) {

        imgSrc = 'url of image';

    } else {
        imgSrc = "another url"
    };

Solution

  • Based on your existing code, you are setting the value of the variable imgSrc.
    In order to update the meta tag, you'll need to reset its content attribute.

    I recommend saving a reference to the element so that you don't need to select it again:

    var $metaOgImage = $('property[og="image:url"]');
    var currentUrl = window.location.href;
    
    if (currentUrl.toLowerCase().indexOf('certain string in url') >= 0) {
      $metaOgImage.attr('content', 'url of image');
    } else {
      $metaOgImage.attr('content', 'another url');
    };