Skip to content

Instantly share code, notes, and snippets.

@georgestephanis
Last active August 14, 2023 18:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgestephanis/0f0cca2c5f1a6cd4aab2 to your computer and use it in GitHub Desktop.
Save georgestephanis/0f0cca2c5f1a6cd4aab2 to your computer and use it in GitHub Desktop.
<?php
class WP_Metatags {
private static $tags = array();
public static function set_tag( $handle, $content, $type = 'name' ) {
if ( ! is_array( self::$tags ) ) {
return new WP_Error( 'metatags_already_printed', __( 'The HTML `meta` tags have already been printed.' ) );
}
self::$tags[ $handle ] = array(
'content' => $content,
'type' => $type,
);
}
public static function print_tags() {
if ( ! is_array( self::$tags ) ) {
return new WP_Error( 'metatags_already_printed', __( 'The HTML `meta` tags have already been printed.' ) );
}
ksort( self::$tags );
foreach ( self::$tags as $handle => $attributes ) {
echo self::render_tag( $handle, $attributes ) . "\r\n";
}
self::$tags = null;
}
public static function render_tag( $handle, $attributes ) {
switch ( $attributes['type'] ) {
case 'name' :
$tag = '<meta name="' . esc_attr( $handle ) . '" ';
break;
case 'charset' :
$tag = '<meta charset="' . esc_attr( $attributes['content'] ) . '" ';
unset( $attributes['content'] );
break;
case 'http-equiv' :
$tag = '<meta http-equiv="' . esc_attr( $handle ) . '" ';
break;
case 'property' : // OG tags use a `property` attribute, not a `name` attribute.
$tag = '<meta property="' . esc_attr( $handle ) . '" ';
break;
default :
// Uncertain if we should support arbitrary types, or if we should just ignore unrecognized types?
$tag = '<meta ' . preg_replace( '/[^\da-z\-_]+/i', '', $attributes['type'] ) . '="' . esc_attr( $handle ) . '" ';
break;
}
if ( isset( $attributes['content'] ) ) {
$tag .= 'content="' . esc_attr( $attributes['content'] ) . '" ';
}
$tag .= "/>";
return $tag;
}
}
add_action( 'wp_head', array( 'WP_Metatags', 'print_tags' ) );
WP_Metatags::set_tag( 'title', 'Meta Title!' );
WP_Metatags::set_tag( 'charset', 'utf-8', 'charset' );
WP_Metatags::set_tag( 'og:title', 'Overridden!', 'property' );
WP_Metatags::set_tag( 'og:title', 'OG Title!', 'property' );
WP_Metatags::set_tag( 'refresh', '30', 'http-equiv' );
WP_Metatags::set_tag( 'random', 'value', 'data-blah');
/* Output in wp_head is:
<meta charset="utf-8" />
<meta property="og:title" content="OG Title!" />
<meta data-blah="random" content="value" />
<meta http-equiv="refresh" content="30" />
<meta name="title" content="Meta Title!" />
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment