简体   繁体   中英

Set og:image and twitter:image meta in wordpress articles with javascript

I'm working on a WP website, and I'm pretty new with code, so after I struggled a whole day to make it work, I just gave up, and decided to ask someone.

I used dynamic meta for all open graphs and twitter cards except image. All the website pages have a container with an article inside; some articles have an image, and some have none. For the ones with no image, I want to use the Company logo.

So I want to use javascript to add og:image and twitter:image to wordpress, but I can't get over one error that says:

document.getElementsByTagName(" ") is not a function

//add image meta tag
addImageMetaTag();

function addImageMetaTag() {
    var imgHolder = document.getElementsByTagName("article")[0];
    var image = imgHolder.getElementsByTagName("img");
    var source;

    function getSource() {
        if (image.length != 0) {
            var source = image[0].getAttribute("src");
        } else {
            var source = "http://link_to_my_default_image.png";
        }
        return source;
    };
    var meta = document.createElement('meta');
    meta.setAttribute("property", "og:image");
    meta.content = source;
    meta.name = "twitter:image";
    document.getElementsByTagName('head')[0].appendChild(meta);
};

Gerald, open graphs and twitter cards are used to create the shared snippet, so it's got nothing to do with crawling.

You were right with your other answer, there were two errors: indeed, I used "getSource" instead of "source" , but Wordpress still wouldn't find the "article" class, because the content loads after the header, so I had "var content = undefined" , so I got the function working by changing it to this:

// add image meta tag
window.addEventListener("load", function() {
    addImageMetaTag();  
});  

function addImageMetaTag() {
    var content = document.getElementById("primary");
    var images = content.querySelectorAll("img");
    var source;

    if (images.length != 0) {
        var source = images[0].getAttribute("src");
    }
    else {
        var source = "http://link_to_my_default_image.png";
    }

    var meta = document.createElement('meta');
    meta.setAttribute("property","og:image");
    meta.content = source;
    meta.name = "twitter:image";
    document.getElementsByTagName('head')[0].appendChild(meta);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM