| 1 |
<?php |
| 2 |
|
| 3 |
/* Twitter Cards |
| 4 |
* |
| 5 |
* Hooks onto the Open Graph protocol and extends it by adding only the tags |
| 6 |
* we need for twitter cards. |
| 7 |
* |
| 8 |
* @see /wp-content/blog-plugins/open-graph.php |
| 9 |
* @see https://dev.twitter.com/docs/cards |
| 10 |
*/ |
| 11 |
function wpcom_twitter_cards_tags( $og_tags ) { |
| 12 |
global $post, $wpdb; |
| 13 |
|
| 14 |
$og_tags['twitter:site'] = '@wordpressdotcom'; |
| 15 |
|
| 16 |
if ( ! is_singular() || ! empty( $og_tags['twitter:card'] ) ) |
| 17 |
return $og_tags; |
| 18 |
|
| 19 |
$img_count = 0; |
| 20 |
foreach ( $og_tags as $key => $value ) { |
| 21 |
if ( 'og:image' != $key || ! is_array( $value ) || empty( $value[0] ) ) |
| 22 |
continue; |
| 23 |
|
| 24 |
$img_count = 0; |
| 25 |
foreach ( (array) $value as $counter => $image ) { |
| 26 |
$og_tags['twitter:image' . $counter] = $image; |
| 27 |
$img_count++; |
| 28 |
if ( $img_count >= 4 ) |
| 29 |
break; // Only 4 images allowed |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
// Figure out what kind of card this is, based on the number of images found |
| 34 |
if ( 0 == $img_count ) { |
| 35 |
// No images = summary |
| 36 |
$card = 'summary'; |
| 37 |
} else if ( $img_count <= 3 ) { |
| 38 |
// < 4 images = photo |
| 39 |
$card = 'photo'; |
| 40 |
$og_tags['twitter:image'] = $og_tags['twitter:image0']; // Rename back to photo format (from gallery) |
| 41 |
unset( $og_tags['twitter:image0'] ); |
| 42 |
for ( $i = 1; $i < 4; $i++ ) { |
| 43 |
unset( $og_tags['twitter:image' . $i] ); // Remove >0 image references |
| 44 |
} |
| 45 |
} else if ( $img_count >= 4 ) { |
| 46 |
// >= 4 images = gallery |
| 47 |
$card = 'gallery'; |
| 48 |
} |
| 49 |
$og_tags['twitter:card'] = $card; |
| 50 |
|
| 51 |
// If we have information on the author/creator, then include that as well |
| 52 |
if ( ! empty( $post ) && ! empty( $post->post_author ) ) { |
| 53 |
$handle = apply_filters( 'jetpack_sharing_twitter_via', '', $post->ID ); |
| 54 |
if ( !empty( $handle ) ) |
| 55 |
$og_tags['twitter:creator'] = '@' . $handle; |
| 56 |
} |
| 57 |
|
| 58 |
return $og_tags; |
| 59 |
} |
| 60 |
|
| 61 |
add_filter( 'jetpack_open_graph_tags', 'wpcom_twitter_cards_tags' ); |
| 62 |
|
| 63 |
function wpcom_twitter_cards_output( $og_tag ) { |
| 64 |
return ( false !== strpos( $og_tag, 'twitter:' ) ) ? preg_replace( '/property="([^"]+)"/', 'name="\1"', $og_tag ) : $og_tag; |
| 65 |
} |
| 66 |
|
| 67 |
add_filter( 'jetpack_open_graph_output', 'wpcom_twitter_cards_output' ); |
| 68 |
|