Skip to content
← Back to Snippets
Code

Open Graph Field Composer

Composes clean Open Graph fields from page metadata while enforcing absolute image URLs and title fallbacks.

Purpose

Composes clean Open Graph fields from page metadata while enforcing absolute image URLs and title fallbacks.

Snippet details

ContextSeoLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

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.
 */

/**
 * Open Graph Field Composer.
 *
 * Purpose:
 * Composes clean Open Graph fields from page metadata while enforcing absolute image URLs and title fallbacks.
 *
 * @param array $page_data Page metadata.
 * @param string $site_name Public site name.
 * @return array Open Graph fields.
 */
function ogSnippetOpenGraphFieldComposer(array $page_data, string $site_name): array {
	$title = 'Untitled Page';
	if (isset($page_data['title']) && trim((string) $page_data['title']) !== '') {
		$title = trim((string) $page_data['title']);
	}

	$description = '';
	if (isset($page_data['description'])) {
		$description = trim(strip_tags((string) $page_data['description']));
	}

	$url = '';
	if (isset($page_data['canonical'])) {
		$url = trim((string) $page_data['canonical']);
	}

	$image = '';
	if (isset($page_data['image'])) {
		$image = trim((string) $page_data['image']);
		if (strpos($image, '//') === 0) {
			$image = 'https:'.$image;
		}
	}

	$type = 'website';
	if (isset($page_data['type']) && trim((string) $page_data['type']) !== '') {
		$type = trim((string) $page_data['type']);
	}

	return array(
		'og:title' => $title,
		'og:description' => $description,
		'og:url' => $url,
		'og:image' => $image,
		'og:type' => $type,
		'og:site_name' => $site_name
	);
}

$serenity_page = array(
	'title' => 'Firefly Cargo Ledger',
	'description' => 'A clean manifest view for Serenity shipments.',
	'canonical' => '//example.com/firefly-cargo-ledger',
	'image' => '//example.com/assets/serenity-cargo.webp'
);

$og_fields = ogSnippetOpenGraphFieldComposer($serenity_page, 'Browncoat Tools');
echo $og_fields['og:title'];