Skip to content

Instantly share code, notes, and snippets.

@kijtra kijtra/meta_tag.php
Last active Mar 17, 2016

Embed
What would you like to do?
#PHP html meta-tag (OGP, FB app, Twitter Cards, etc) helper.
<?php
function meta_tag()
{
static $buffer = array();
$charset = 'utf-8';
$num = func_num_args();
$args = func_get_args();
if (2 === $num && is_string($args[0]) && is_string($args[1])) {
$name = trim(htmlspecialchars($args[0], ENT_COMPAT, $charset));
$content = htmlspecialchars($args[1], ENT_COMPAT, $charset);
if('charset' == $name) {
$buffer[$name][] = '<meta charset="'.$content.'">';
} else {
$prop = 'name';
if (0 === strpos($name, 'og:') || 0 === strpos($name, 'fb:')) {
$prop = 'property';
} elseif(false !== strpos($name, '-')) {
$prop = 'http-equiv';
}
if (false !== strpos($name, ':image')) {
if (empty($buffer[$name])) {
$buffer[$name] = array();
}
$buffer[$name][$content] = '<meta '.$prop.'="'.$name.'" content="'.$content.'">';
} else {
$buffer[$name] = '<meta '.$prop.'="'.$name.'" content="'.$content.'">';
}
}
} elseif(1 === $num && is_array($args[0])) {
foreach($args[0] as $key => $value) {
if (is_array($value)) {
foreach($value as $val) {
meta($key, $val);
}
} else {
meta($key, $value);
}
}
} elseif (0 === $num && !empty($buffer)) {
ksort($buffer);
$tags = array();
foreach($buffer as $value) {
if (is_array($value)) {
foreach($value as $val) {
$tags[] = $val;
}
} else {
$tags[] = $value;
}
}
return implode(PHP_EOL, $tags).PHP_EOL;
}
}
/*
// Usage
meta_tag('description', 'Page Description');
meta_tag('twitter:card', 'summary');
meta_tag('og:image', 'http://example.com/image1.jpg');
meta_tag('og:image', 'http://example.com/image2.jpg');
// OR
meta_tag(array(
'description' => 'Page Description',
'twitter:card' => 'summary',
'og:image' => array(
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
),
));
// Render
echo meta();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.