Created
June 22, 2013 23:08
-
-
Save petenelson/5843020 to your computer and use it in GitHub Desktop.
WordPress: Twitter Card
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: GGA Twitter Card | |
Description: Adds Twitter card meta tags to the header | |
Author: @GunGeekATX | |
*/ | |
add_action('wp_head', 'gga_twitter_card_wp_head'); | |
function gga_twitter_card_wp_head() { | |
$html[] = "<!-- GGA Twitter Card -->"; | |
$card_type = 'summary'; | |
$is_image = false; | |
$url = ''; | |
$title = ''; | |
$url = is_attachment() || is_single() ? get_permalink() : home_url(); | |
if (is_attachment() ) { | |
$title = get_the_title(); | |
if (has_excerpt()) | |
$description = get_the_excerpt(); | |
$attachment = wp_get_attachment_image_src(get_the_id(), 'full'); | |
$is_image = wp_attachment_is_image(get_the_id()); | |
if ($is_image) | |
$card_type = 'photo'; | |
} else if (is_single()) { | |
$title = get_the_title() . ' | ' . get_bloginfo('name'); | |
if (has_excerpt()) | |
$description = get_the_excerpt(); | |
$thumbnail_id = get_post_thumbnail_id(); | |
if ($thumbnail_id) | |
$attachment = wp_get_attachment_image_src($thumbnail_id); | |
else { | |
// see if we have any attachments, if so, grab the first one | |
$attachments = get_children(array( | |
'post_parent' => get_the_id(), | |
'post_type' => 'attachment', | |
'numberposts' => 1, | |
'post_status' => 'any' | |
)); | |
if ($attachments && count($attachments) > 0) { | |
foreach ($attachments as $att) | |
$attachment = wp_get_attachment_image_src($att->ID); | |
} | |
} | |
} else { | |
$title = get_bloginfo('name', 'display'); | |
$description = get_bloginfo( 'description' ); | |
} | |
$html[] = "<meta name=\"twitter:card\" content=\"{$card_type}\" />"; | |
$html[] = "<meta name=\"twitter:title\" content=\"" . esc_attr($title) . "\" />"; | |
if (isset($description) && !empty($description)) | |
$html[] = "<meta name=\"twitter:description\" content=\"" . esc_attr($description) . "\" />"; | |
$html[] = "<meta name=\"twitter:url\" content=\"{$url}\" />"; | |
if ($attachment && $attachment !== false) { | |
$html[] = "<meta name=\"twitter:image\" content=\"" . $attachment[0] . "\" />"; | |
if ($is_image) { | |
$html[] = "<meta name=\"twitter:image:width\" content=\"{$attachment[1]}\">"; | |
$html[] = "<meta name=\"twitter:image:height\" content=\"{$attachment[2]}\">"; | |
} | |
} | |
$html[] = "<!-- GGA Twitter Card end -->"; | |
foreach ($html as $h) | |
echo $h . "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment