Skip to content

Instantly share code, notes, and snippets.

@aosipov
Created January 17, 2018 21:01
Show Gist options
  • Save aosipov/91967f86c8ad0c766f04596522e4fd15 to your computer and use it in GitHub Desktop.
Save aosipov/91967f86c8ad0c766f04596522e4fd15 to your computer and use it in GitHub Desktop.
social sharing with Pinterest first image
//Get the first image from the post
function get_first_image_url() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
// Defines a default image here
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}
// Social sharing shortcode
/** <?php echo do_shortcode('[social_sharing]') ; ?> */
function social_sharing()
{
// Get current page URL
$pageURL = urlencode(get_permalink());
// Get current page title
$pageTitle = str_replace( ' ', '%20', get_the_title());
$postMeta = get_post_meta(get_the_ID(), 'description', true);
// Get Post Thumbnail for pinterest
global $post;
$postThumbnail = get_first_image_url();
// Facebook URL
$facebookURL = 'https://www.facebook.com/sharer/sharer.php?u='.$pageURL;
// Pinterest
$pinterestURL = 'https://pinterest.com/pin/create/button/?url='.$pageURL.'&amp;media='.$postThumbnail.'&amp;description='.$pageTitle.' - '.$postMeta;
return'
<div class="social-sharing-container">
<a class="btn social-sharing-btn btn-facebook" target="_new" href="'.$facebookURL.'"><i class="fa fa-facebook"></i></a>
<a class="btn social-sharing-btn btn-pinterest" target="_new" href="'.$pinterestURL.'" data-pin-custom="true" target="_blank"><i class="fa fa-pinterest"></i></a>
<a class="btn social-sharing-btn btn-email" href="mailto:?subject='.$pageTitle.'&body='.$pageURL.'"><i class="fa fa-envelope"></i></a>
</div>
';
}
add_shortcode("social_sharing", "social_sharing");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment