如何动态获取原始图片

huangapple go评论76阅读模式
英文:

How to get the OG image Dynamically

问题

我正在进行的项目是一个酒店项目。不同页面有不同的主图像。

例如-
如果有人将关于我们页面分享到Facebook,关于我们页面中的主图像应显示在链接下方。如果有人将主页分享到Facebook,主页中的主图像应显示在链接下方。在og:image中只能有一个链接,因为header.php文件是我用于所有页面的相同文件。

是否有办法可以使用PHP或JS来实现这个功能。

提前谢谢。

<meta property="og:image" id="ogImage" content="">
<script>
  function setOGImageURL() {
    const ogImageElement = document.querySelector('.entry-header-image');
    if (ogImageElement) {
      const ogImageURL = ogImageElement.getAttribute('src');
      console.log(ogImageElement)
      const ogImageTag = document.getElementById('ogImage');
      ogImageTag.setAttribute('content', ogImageURL);
    }
  }

  window.onload = function() {
    setOGImageURL();
  };
</script>

我试图从这段代码中实现这个功能,但没有成功。

英文:

The project I'm working on is a project for a hotel. There are different images for different pages as a main image.
For Example-
If someone shares the about us page to facebook, the main image in the about us page should be displayed below the link. If someone shares the home page to facebook, the main image in the home page should be displayed below the link. There can only be one link in the og:image because the header.php file is the same file that I'm using to all pages

Is there any way that I can do this using php or js.

Thank you in advance.

&lt;meta property=&quot;og:image&quot; id=&quot;ogImage&quot; content=&quot;&quot;&gt;
  &lt;script&gt;
    function setOGImageURL() {
      const ogImageElement = document.querySelector(&#39;.entry-header-image&#39;);
      if (ogImageElement) {
        const ogImageURL = ogImageElement.getAttribute(&#39;src&#39;);
        console.log(ogImageElement)
        const ogImageTag = document.getElementById(&#39;ogImage&#39;);
        ogImageTag.setAttribute(&#39;content&#39;, ogImageURL);
      }
    }

    window.onload = function() {
      setOGImageURL();
    };
  &lt;/script&gt;

I was trying to do from this code. But it didn't work

答案1

得分: 4

你可以使用PHP来实现这个,例如:

<meta property="og:image" id="ogImage" content="<?php echo getOGImage(getCurrentURL()); ?>">

但是,为了使其正常工作,你需要实现getOGImagegetCurrentURL这两个函数。getOGImage函数应该如下所示:

function getOGImage($url) {
    // 在这里添加你的逻辑以确定图像路径,不要忘记返回结果
}

以及

function getCurrentURL() {
    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')   
         $url = "https://";   
    else  
         $url = "http://";   
    // 将主机名(域名、IP)附加到URL
    $url .= $_SERVER['HTTP_HOST'];   
    
    // 将请求的资源位置附加到URL
    $url .= $_SERVER['REQUEST_URI'];    
      
    return $url;  
}

第二段代码的灵感来自于https://www.javatpoint.com/how-to-get-current-page-url-in-php

不要使用JavaScript,因为Facebook不会识别它,特别是当用户的浏览器中关闭了JavaScript时,你的标签需要在JavaScript执行任何更改之前已经加载。最好的方法是在服务器端将最终的图像路径生成到你的meta标签中,这样我们感兴趣的HTML解析器将从一开始就获得正确的结果。

英文:

You can definitely do this with PHP, like:

&lt;meta property=&quot;og:image&quot; id=&quot;ogImage&quot; content=&quot;&lt;?php echo getOGImage(getCurrentURL()); ?&gt;&quot;&gt;

But, in order to make this work, you will need to implement both getOGImage and getCurrentURL. So, this is how getOGImage will look alike:

function getOGImage($url) {
    //your logic here that determines the image path, don&#39;t forget to return the result
}

and

function getCurrentURL() {
    if(isset($_SERVER[&#39;HTTPS&#39;]) &amp;&amp; $_SERVER[&#39;HTTPS&#39;] === &#39;on&#39;)   
         $url = &quot;https://&quot;;   
    else  
         $url = &quot;http://&quot;;   
    // Append the host(domain name, ip) to the URL.   
    $url.= $_SERVER[&#39;HTTP_HOST&#39;];   
    
    // Append the requested resource location to the URL   
    $url.= $_SERVER[&#39;REQUEST_URI&#39;];    
      
    return $url;  
}

This second code was inspired based on https://www.javatpoint.com/how-to-get-current-page-url-in-php

Don't do this with Javascript, because Facebook will not pick that up, especially when Javascript is turned off in the user's browser and, your tag needs to be already loaded for Javascript to perform any changes. You are much better off if you generate your final image path into your meta at server-side, so the HTML parser of our interest will get the correct result right from the start.

答案2

得分: 1

使用JavaScript执行此任务的问题在于,Facebook的爬虫在抓取您的网站以查找Open Graph标签时不执行JavaScript。因此,它无法看到您的JavaScript代码所做的任何更改。

您可以通过使用服务器端语言如PHP来实现此目标,根据当前页面动态更改meta标签内容。

<?php 
    // 获取当前页面的URL
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $imgUrl = '';

    // 根据URL设置图像URL
    if (strpos($url, 'about') !== false) {
        $imgUrl = 'http://yourwebsite.com/path/to/about/image.jpg';
    } else if (strpos($url, 'home') !== false) {
        $imgUrl = 'http://yourwebsite.com/path/to/home/image.jpg';
    } else {
        // 如果未检测到特定页面,则设置默认图像
        $imgUrl = 'http://yourwebsite.com/path/to/default/image.jpg';
    }
?>
<!DOCTYPE html>
<html>
<head>
    <!-- 其他标签... -->
    <meta property="og:image" content="<?php echo $imgUrl; ?>">
    <!-- 其他标签... -->
</head>
<body>
<!-- 您的页面内容在此... -->
</body>
</html>

此脚本获取当前URL并检查是否包含特定字符串(在本例中为'about'和'home')。根据找到的字符串,它将$imgUrl设置为相应图像的URL。然后,该值被回显到og:image meta标签的content属性中。

这样,当Facebook抓取页面时,它会看到每个特定页面的正确og:image URL。

只需记住将图像URL替换为您的实际图像URL即可。

英文:

The problem with using JavaScript for this task is that Facebook's scraper does not execute JavaScript when it scrapes your website to find the Open Graph tags. Therefore, it won't be able to see any changes made by your JavaScript code.

You can achieve this by using server-side language like PHP to dynamically change the meta tag content based on the current page.

&lt;?php 
    // get the current page URL
    $url = &quot;http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;
    $imgUrl = &#39;&#39;;

    // based on the URL, set the image URL
    if (strpos($url, &#39;about&#39;) !== false) {
        $imgUrl = &#39;http://yourwebsite.com/path/to/about/image.jpg&#39;;
    } else if (strpos($url, &#39;home&#39;) !== false) {
        $imgUrl = &#39;http://yourwebsite.com/path/to/home/image.jpg&#39;;
    } else {
        // set a default image if no specific page is detected
        $imgUrl = &#39;http://yourwebsite.com/path/to/default/image.jpg&#39;;
    }
?&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;!-- other tags... --&gt;
    &lt;meta property=&quot;og:image&quot; content=&quot;&lt;?php echo $imgUrl; ?&gt;&quot;&gt;
    &lt;!-- other tags... --&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- your body content here... --&gt;
&lt;/body&gt;
&lt;/html&gt;

This script gets the current URL and checks if it contains certain strings (in this case 'about' and 'home'). Depending on which string is found, it sets $imgUrl to the URL of the corresponding image. This value is then echoed into the content attribute of the og:image meta tag.

This way, when Facebook scrapes the page, it sees the correct og:image URL for each specific page.

Just remember to replace the image URLs with the actual URLs of your images.

答案3

得分: 1

看起来你的代码方向是正确的。然而,为了确保它能正确运行,你需要确保在你想在Facebook上分享的特定页面上存在**".entry-header-image"元素。验证一下具有类"entry-header-image"**的元素是否存在于"关于我们"页面和首页。

另外,检查一下**"ogImageElement""src"属性是否正确指向所需的图片URL。你可以使用"console.log"输出"ogImageURL"**,并验证它是否包含正确的图片URL。

如果代码仍然不起作用,请确保**" :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定