0

I'm trying to add Twitter Card functionality to a Wordpress blog so that whenever someone posts a link to an article on Twitter, the card displays. Here is the code I put in functions.php of my theme to insert into the head:

function add_twitter_cards() {
if(is_single()) {
$tc_url    = get_permalink();
$tc_title  = get_the_title();
$tc_description   = get_the_excerpt();
$tc_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full );
$tc_image_thumb  = $tc_image[0];
$tc_author   = str_replace('@', '', get_the_author_meta('twitter'));?>

<meta name="twitter:card" value="summary" />
<meta name="twitter:site" value="@username" />
<meta name="twitter:title" value="<?php echo $tc_title; ?>" />
<meta name="twitter:description" value="<?php echo $tc_description; ?>" />
<meta name="twitter:url" value="<?php echo $tc_url; ?>" />
    <?php if($tc_image) { ?>
  <meta name="twitter:image" value="<?php echo $tc_image_thumb; ?>" />
    <?php } if($tc_author) { ?>
    <meta name="twitter:creator" value="@<?php echo $tc_author; ?>" />
<?
    }
    }
}

Problem is that the blog has no manually defined excerpts, so the twitter:description field output is blank. I then tried to replace get_the_excerpt with this to pull the first 20 words of the article:

apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 20 ) );

But it's inserting HTML code when I need the plain text. Any tips?

  • what if you used wp_trim_words( get_the_content(), 40, '...' ); – Castiblanco Aug 25 '18 at 13:48
  • Then the description field in the article page shows up empty (two quotes with nothing inside). – Cableboy Aug 25 '18 at 14:26
1

As you can see from the source of get_the_excerpt there is a filter toward the end to modify the result. This is probably the most future proof approach. If at some point the blog will have manually written excerpts, these will be used. That would not be the case if you write a custom function for the twitter card. So, let's start here:

add_filter ('get_the_excerpt', 'wpse312463_custom_excerpt');

Now there are three things you want to do: remove shortcodes, remove html and limit the amount of words. Here we go:

function wpse312463_custom_excerpt ($excerpt, $post) {
  if (empty ($excerpt)) $excerpt = $post->content;
  $excerpt = strip_tags (strip_shortcodes ($excerpt));
  $excerpt = wp_trim_words ($excerpt, 55);
  return $excerpt;
  }

You could even pack the last three lines into one statement, but that isn't very readable.

  • If I add this filter, what do I change this line to? $tc_description = get_the_excerpt(); – Cableboy Aug 25 '18 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.