Search code examples
javascriptphphtmlfacebook-opengraph

How to get the OG image Dynamically


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.

<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>

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


Solution

  • Since you're inlcuding header.php in all files you can try getting the current script running :

    $currentPage = basename($_SERVER['PHP_SELF'], ".php");
    

    Define an array that has every page name associated to it's own og:image URL

    $ogImages = array(
      "profile" => "path_to_profile_og_image.jpg",
      "settings" => "path_to_settings_og_image.jpg",
     );
    

    and then check if the current page has a corresponding og:image URL

    if (array_key_exists($currentPage, $ogImages)) {
    $ogImageUrl = $ogImages[$currentPage];
     echo '<meta property="og:image" content="' . $ogImageUrl . '">';
     }
    

    NOTE :

    I was using the same solution for Dynamic Profiles og:Image and <head> titles

    <!-- Facebook Meta Tags -->
    <meta property="og:url" content="<?php echo $system->url; ?>">
    <meta property="og:type" content="website">
    <meta property="og:title" content="<?php echo ($currentPage == 'profile') ? $profileAccount->name . ' (@' . $profileAccount->username . ')' :  'Simplify our Online Presence with Profily'; ?>">
    <meta property="og:description" content="<?php echo ($currentPage == 'profile') ? 'Follow my Profily for the latest' :  'The one and only page for all your important links'; ?>">
    <meta property="og:image" content="<?php echo ($currentPage == 'profile') ? $system->url . '/images/' . $profileAccount->avatar :  $system->url . '/content/images/second-banner.webp'; ?>">