Use title attribute for Pinterest description

When users pin a specific image in your post, Pinterest works through the following hierarchy to find the pin description. The first one it finds, it uses.

  1. data-pin-description attribute, which is a custom attribute specifically for the Pinterest description. You can manage this using a plugin like Tasty Pins. For more information, see our article on Tasty Pins integration.
  2. Image title attribute
  3. Alt text
  4. Post title
  5. Post content

The Shared Counts pin button works a bit differently. It uses the post title as the description unless you’re using the Shared Counts – Pinterest Image extension and specified a custom description.

While it’s not recommended to use the title attribute specifically for the Pinterest description, if you have already done so for thousands of images on your site, use the code below to use this title as the Pinterest description for Shared Counts.

Note: this will only work for posts that are using the new block editor (aka: Gutenberg).

This code snippet goes in a core functionality plugin or Code Snippets.

/** * Pinterest button, use image title as description * @link https://sharedcountsplugin.com/2020/05/15/use-title-attribute-for-pinterest-description/ * * @param array $link * @param int $post_id * @param string $style * @return array $link */ function be_pinterest_image_description( $link, $post_id, $style ) { if( ! ( 'pinterest' === $link['type'] && has_post_thumbnail( $post_id ) && empty( $link['parsed'] ) ) ) return $link; $blocks = parse_blocks( get_post( $post_id )->post_content ); foreach( $blocks as $block ) { if( 'core/image' === $block['blockName'] && get_post_thumbnail_id( $post_id ) == $block['attrs']['id'] ) { $link['parsed'] = true; $doc = new DOMDocument(); libxml_use_internal_errors(true); $doc->loadHTML($block['innerHTML']); libxml_clear_errors(); $xpath = new DOMXPath($doc); $title = $xpath->evaluate("string(//img/@title)"); if( !empty( $title ) ) $link['link'] = 'https://pinterest.com/pin/create/button/?url=' . $link['url'] . '&media=' . $link['img'] . '&description=' . rawurlencode( wp_strip_all_tags( $title ) ); } } return $link; } add_filter( 'shared_counts_link', 'be_pinterest_image_description', 9, 3 );

Filters used:

Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.