|
<?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!" /> |
|
|
|
*/ |