Open Graph Tag Builder
Builds Open Graph meta tag data for pages and detail items.
Function signature
ogBuildOpenGraphTags(title, description, url, options = array())
Categories
- SEO and Routing
Parameters
titleHuman-facing title used for metadata, schema, or alt text.descriptionPlain-text description used for Open Graph or schema output.urlCanonical URL associated with the generated metadata or schema.optionsOptional documented policy controls for the helper.Return value
Public-safe status string returned by the function for controller branching or logging.
- success
- message
- data
Compatibility
Existing function name, slug, path, and call order preserved; advertised metadata corrected to the actual source behavior.
Minimum PHP version: 7.4
Security notes
Use caller-owned allowlists and context-specific escaping; validate file paths, routes, email tokens, cart totals, discount rules, and tax-region rules before production use.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Builds Open Graph meta tag data for pages and detail items.
*
* Primary use case: Social sharing and previews.
* Typical inputs: page title, description, image, canonical.
* Typical output: tag data.
*
* Implementation note: Use absolute/protocol-relative URLs according to site policy.
*
* @return array Structured result data with success, message, and data keys.
*/
function ogBuildOpenGraphTags($title, $description, $url, $options = array()) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$title = trim(strip_tags((string)$title));
$description = trim(strip_tags((string)$description));
$url = trim((string)$url);
if (!is_array($options)) {
$options = array();
}
if (empty($title) || empty($url)) {
$result['message'] = 'Open Graph title and URL are required.';
return $result;
}
if (!preg_match('/^(\/\/|https:\/\/)/i', $url)) {
$result['message'] = 'Open Graph URL must be protocol-relative or HTTPS.';
return $result;
}
if (preg_match('/^https?:\/\/www\./i', $url) || preg_match('/^\/\/www\./i', $url)) {
$result['message'] = 'Open Graph URL must not use www.';
return $result;
}
$image = '';
if (!empty($options['image'])) {
$image = trim((string)$options['image']);
if (!preg_match('/^(\/\/|https:\/\/)/i', $image)) {
$image = '';
}
}
$type = 'website';
if (!empty($options['type'])) {
$type = trim(strip_tags((string)$options['type']));
}
$tags = array(
'og:title' => $title,
'og:description' => $description,
'og:type' => $type,
'og:url' => $url
);
if (!empty($image)) {
$tags['og:image'] = $image;
}
$result['success'] = true;
$result['message'] = 'Open Graph tags built.';
$result['data'] = array('tags' => $tags);
return $result;
}