Generating Facebook Open Graph meta tags dynamically

Generating Facebook Open Graph meta tags dynamically

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Facebook Open Graph Meta Tags Dynamically

Building dynamic pages for social sharing requires more than just hard-coding HTML. When a URL structure changes based on query parameters, your Open Graph (OG) meta tags must adapt in real-time to ensure platforms like Facebook render the correct preview. This process involves parsing incoming data, applying sensible defaults, and constructing valid HTML that survives the scraper's crawl.

The core challenge lies in decoupling the view logic from the data source. You need a mechanism to inspect $_GET or $_POST variables immediately upon request arrival. If these parameters are absent, the application should not break; instead, it must fall back to predefined constants. In a PHP environment, this is handled by initializing an associative array and conditionally overwriting keys only when values exist.

Consider a scenario where a developer builds a restaurant finder. The URL might look like index.php?type=bistro&locale=de_DE, but users often share links with incomplete parameters. Your meta tag generator must handle the missing type or locale gracefully. You can implement this by checking if a parameter is an empty string and assigning a fallback value immediately:

$params = array();
if (count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}

// Apply defaults only if the incoming value is empty
if ($params['type'] == "") $params['type'] = "restaurant";
if ($params['locale'] == "") $params['locale'] = "en_US";
if ($params['title'] == "") $params['title'] = "default title";
if ($params['image'] == "") $params['image'] = "thumb";
if ($params['description'] == "") $params['description'] = "default description";

Once the data is normalized, generating the <head> section requires careful attention to syntax. The most common pitfall here is mixing static PHP logic with dynamic output inside HTML attributes without proper escaping or quoting. While simple values might pass, special characters in titles or descriptions can break the HTML structure if not handled correctly. Furthermore, the og:url property must point directly to the current request URI. Constructing this manually by echoing parameters back into the URL string is risky; it often leads to malformed URLs if the input contains ampersands or quotes.

However, in many legacy setups or specific scraping contexts, you might need to explicitly construct the full URL string for the og:url tag to ensure the scraper validates the exact parameter set that generated the page. The implementation below demonstrates how to output the necessary meta tags, including the namespace prefix required for custom types:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        
        <!-- Constructing the URL with dynamic parameters -->
        <meta property="og:url" content="http://mysite.com/index.php?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="http://mysite.com/img/<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>
    </head>
</html>

This approach allows the debugger tool to accept any combination of parameters, regardless of order. Whether the URL is http://mysite.com/index.php?type=restaurant&title=luigis or a subset like http://mysite.com/index.php?locale=de_DE&type=bistro, the meta tags will reflect the active state of those variables.

Once these dynamic OG tags are in place, you can leverage them to publish actions directly to a user's stream. The Facebook API allows you to post custom actions that reference the specific content defined in your URL parameters. For instance, if the current page represents "having lunch at Arnold," you can trigger a have_lunch action:

function postRestaurant() {
    FB.api('me/MY_APP_NAMESPACE:have_lunch?start_time=2000-12-12T04:00:00&expires_in=7200&restaurant=' . 
           urlencode(getRedirectURI() . '?type=restaurant&description=arnold&title=stalone'), 'post', function (response) {
        if (!response || response.error) {
            console.log('postRestaurant: Error occurred => ' + response.error.message);
        } else {
            console.log('postRestaurant: Post was successful! Action ID: ' + response.id);
        }
    });
}

By encoding the redirect URI and including the dynamic parameters in the action payload, you create a cohesive experience where the shared URL matches the content of the post. This ensures consistency between the preview Facebook displays and the actual interaction happening on your platform.

Our network