Skip to content

Instantly share code, notes, and snippets.

@radist2s
Created July 12, 2017 13:45
Show Gist options
  • Save radist2s/8d5f60664ea0c9929fa5fba723c1ae0d to your computer and use it in GitHub Desktop.
Save radist2s/8d5f60664ea0c9929fa5fba723c1ae0d to your computer and use it in GitHub Desktop.
Social Share boilerplate
define(['sharer'], function() {
Array.prototype.forEach.call(document.querySelectorAll('.socialShare'), function (shareLinksNode) {
socialShare(shareLinksNode)
})
})
<?php
class SocialShare
{
static $instance;
protected $url = null;
public static $fb_app_id = 'fb_prod_id';
public static $vk_app_id = 'vk_prod_id';
static function is_home()
{
return is_front_page() OR is_home();
}
public function url($esc_attr = false)
{
$url =& $this->url;
if ($url === null)
{
$queried_object = get_queried_object();
if ($queried_object instanceof WP_Post)
{
$url = get_permalink();
}
elseif (is_object($queried_object) AND !empty($queried_object->term_id))
{
$url = get_term_link($queried_object);
}
else
{
$url = site_base_url();
}
}
$site_url_regexp = addslashes(site_base_url());
$url = preg_replace("~^$site_url_regexp~iu", site_base_url('', TRUE), $url);
$url = user_trailingslashit($url);
return $url ? esc_attr($url) : $url;
}
public function image($esc_attr = false)
{
static $image = null;
if ($image === null)
{
if (!$image = get_field('og_image', static::is_home() ? 'options' : NULL))
{
$image = get_field('og_image', static::is_home() ? NULL : 'options');
}
if (!$image AND $thumbnail_id = get_post_thumbnail_id())
{
$attachment_image = wp_get_attachment_image_src($thumbnail_id, 'original');
if ($attachment_image AND is_array($attachment_image))
{
$image = reset($attachment_image);
}
}
}
return $esc_attr ? esc_attr($image) : $image;
}
public function title($esc_attr = false)
{
static $title = null;
if ($title === null)
{
$queried_object = get_queried_object();
if (static::is_home())
{
$title = trim(get_field('og_title', 'options'));
}
elseif ($queried_object instanceof WP_Post)
{
$title = trim(get_field('og_title'));
if (!$title)
{
$title = trim(get_post()->post_title);
}
}
elseif (is_object($queried_object) AND !empty($queried_object->term_id))
{
$title = $queried_object->name . ' – ' . get_bloginfo();
}
if (!$title)
{
$title = get_bloginfo();
}
$title = html_entity_decode($title, ENT_COMPAT, 'UTF-8');
}
return $esc_attr ? esc_attr($title) : $title;
}
public function description($esc_attr = false)
{
static $description = null;
if ($description === null)
{
$description = trim(get_field('og_description', static::is_home() ? 'options' : NULL));
if (!$description)
{
$description = trim(get_field('og_description', static::is_home() ? NULL : 'options'));
}
if (!$description AND get_post_type() === 'post')
{
$description = trim(get_field('undertitle'));
}
if (!$description)
{
if (!$description = trim(get_the_excerpt()))
{
$description = get_bloginfo('description');
}
}
$description = html_entity_decode($description, ENT_COMPAT, 'UTF-8');
}
return $esc_attr ? esc_attr($description) : $description;
}
public function site_name($esc_attr = false)
{
$site_name = null;
if ($site_name === null)
{
$site_name = trim($title = get_bloginfo());
$site_name = html_entity_decode($site_name, ENT_COMPAT, 'UTF-8');
}
return $esc_attr ? esc_attr($site_name) : $site_name;
}
public function facebook($unique_only = false)
{
$query = http_build_query(array(
'app_id' => static::$fb_app_id,
'link' => $unique_only ? '%og:url%' : (self::url() ? self::url() : site_url()),
'picture' => $unique_only ? '%og:image%' : (self::image() ? self::image() : ''),
'name' => $unique_only ? '%og:title%' : self::title(),
'description' => $unique_only ? '%og:description%' : self::description(),
'display' => 'popup',
'redirect_uri' => get_template_directory_uri() . '/includes/self-close.html',
), '', '&', PHP_QUERY_RFC3986);
return "http://www.facebook.com/dialog/feed?{$query}";
}
public function twitter($unique_only = false)
{
$query = http_build_query(array(
'url' => $unique_only ? '%og:url%' : self::url(),
'text' => $unique_only ? '%og:title%' : self::title()
), '', '&', PHP_QUERY_RFC3986);
return "http://twitter.com/share?{$query}";
}
public function vk($unique_only = false)
{
$query = http_build_query(array(
'url' => $unique_only ? '%og:url%' : self::url(),
'title' => $unique_only ? '%og:title%' : self::title(),
'description' => $unique_only ? '%og:description%' : self::description(),
'image' => $unique_only ? '%og:image%' : self::image(),
'noparse' => 'true'
), '', '&', PHP_QUERY_RFC3986);
return "http://vk.com/share.php?{$query}";
}
public function ok($unique_only = false)
{
$query = http_build_query(array(
'st.comments' => $unique_only ? '%og:description%' : self::description(),
'st._surl' => $unique_only ? '%og:url%' : self::url()
), '', '&', PHP_QUERY_RFC3986);
return "http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1&{$query}";
}
public static function head()
{
if (!self::$instance)
{
self::$instance = new static;
}
$instance =& self::$instance;
?>
<meta property="og:url" content="<?php echo $instance->url(true) ?>" />
<meta property="og:site_name" content="<?php echo $instance->site_name(true) ?>" />
<meta property="og:title" content="<?php echo $instance->title(true) ?>" />
<meta property="og:description" content="<?php echo $instance->description(true) ?>" />
<meta property="og:image" content="<?php echo $instance->image(true) ?>" />
<meta property="fb:app_id" content="<?php echo static::$fb_app_id?>" />
<?php
}
/**
* @param array|string $params array(url => '', ) || '//url/path'
*/
public static function links($params = array())
{
$sharer = new SocialShare;
if (is_array($params))
{
extract($params);
}
elseif (is_string($params))
{
$url = $params;
}
if (isset($url) AND $url = trim($url))
{
if (!preg_match('~(https?:|^)\/\/~iu', $url))
{
$url = site_base_url($url);
}
$sharer->url = $url;
}
include get_template_directory() . '/parts/share-links.php';
}
public static function btn_like_fb_standalone($url = '')
{
if (!self::$instance)
{
self::$instance = new static;
}
if (!$url)
{
$url = self::$instance->url($url);
}
$url = rawurlencode($url);
ob_start();
?>
<iframe name="f20fec5168" frameborder="0" allowtransparency="true"
class="btn-like-standalone btn-like-standalone--fb"
allowfullscreen="true" scrolling="no" title="fb:share_button Facebook Social Plugin"
src="http://www.facebook.com/v2.5/plugins/share_button.php?app_id=<?= static::$fb_app_id ?>&amp;channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2FTlA_zCeMkxl.js%3Fversion%3D41%23cb%3Dfe5b70b64%26relation%3Dparent.parent&amp;href=<?= $url ?>&amp;layout=button_count&amp;locale=ru_RU&amp;sdk=joey"
style="border: none; visibility: visible; width: 130px; height: 20px;"></iframe>
<?
return ob_get_clean();
}
public static function btn_like_vk_standalone($url = '')
{
if (!self::$instance)
{
self::$instance = new static;
}
if (!$url)
{
$url = self::$instance->url($url);
}
$url = rawurlencode($url);
$script_id = rand(0, 9999) . time();
ob_start()
?>
<script id="vk-share-script-<?= $script_id ?>">
!function () {
var loader = document.createElement('script')
loader.onload = loader.onreadystatechange = function() {
if (this.readyState && (this.readyState != 'loaded' || this.readyState != 'complete')) {
return
}
delete loader.onreadystatechange
delete loader.onload
vkLoadedCallback()
}
loader.charset = 'windows-1251'
loader.async = 'async'
loader.src = 'http://vk.com/js/api/share.js?93'
document.head.appendChild(loader)
function vkLoadedCallback() {
var scriptEl = document.getElementById('vk-share-script-<?= $script_id ?>')
scriptEl.insertAdjacentHTML('afterend', VK.Share.button(false, {
type: 'round',
text: 'Поделиться',
height: 20
}))
scriptEl.parentNode.removeChild(scriptEl)
}
}()
</script>
<?
return ob_get_clean();
}
public static function btn_tweet_standalone($url = '')
{
if (!self::$instance)
{
self::$instance = new static;
}
if (!$url)
{
$url = self::$instance->url($url);
}
$btn_id = 'twitter-btn-' . rand(0, 99999) . microtime(true);
ob_start();
?>
<div class="btn-like-standalone btn-like-standalone--twitter" id="<?php echo $btn_id ?>"></div>
<script>
!function () {
var loader = document.createElement('script')
loader.onload = loader.onreadystatechange = function() {
if (this.readyState && (this.readyState != 'loaded' || this.readyState != 'complete')) {
return
}
delete loader.onreadystatechange
delete loader.onload
twitterLoadedCallback()
}
function twitterLoadedCallback() {
twttr.widgets.createShareButton('<?php echo $url ?>', document.getElementById('<?php echo $btn_id ?>'))
}
loader.async = 'async'
loader.src = '//platform.twitter.com/widgets.js'
document.head.appendChild(loader)
}()
</script>
<?php
return ob_get_clean();
}
}
define(['underscore'], function (_) {
var ogAttrRegex = /%(og:[\S]+)%/g
var methods = {
init: function (options) {
if (this.hasAttribute('social-attached')) {
return
}
this.setAttribute('social-attached', true)
var settings = {
callback: function ($this) {},
linkHrefFilter: null,
linkComponentFilter: null
}
(_ || window.jQuery).extend(settings, options)
return this.addEventListener('click', methods.onLinkClick.bind(this, settings))
},
onLinkClick: function (settings, e) {
var linkNode,
rootNode = this,
socialNetwork
while (!socialNetwork) {
linkNode = linkNode ? linkNode.parentNode : e.target
if (!linkNode || rootNode === linkNode) {
return
}
socialNetwork = linkNode.getAttribute('data-network')
}
e.preventDefault()
if (!linkNode.getAttribute('query-data-replaced')) {
methods.replaceLinkData(linkNode, settings)
linkNode.getAttribute('query-data-replaced', true)
}
var width = 650,
height = 450,
left = Math.floor(screen.width / 2 - width / 2),
top = Math.floor(screen.height / 2 - height / 2)
var windowParams = 'height=' + height + ',width=' + width + ',left=' + left + ',top=' + top
+ ',toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no'
var url = linkNode.href || decodeURI(linkNode.getAttribute('data-href')),
title = linkNode.title
var popup = window.open(url, title, windowParams)
try {
popup.document.title = title
}
catch (e) {}
settings.callback(linkNode)
window.ga && ga('send', 'event', 'SocialShareRequest', socialNetwork)
},
replaceLinkData: function (linkNode, settings) {
if (settings.linkHrefFilter instanceof Function) {
settings.linkHrefFilter(linkNode)
}
var query = linkNode.search || ''
var queryVars = {}
query.substr(1).split('&').forEach(function (item) {
var itemParts = item.split('=')
queryVars[itemParts[0]] = itemParts[1]
})
Object.keys(queryVars).forEach(function (attr) {
var val
try {
val = decodeURIComponent(queryVars[attr])
}
catch (e) {
val = queryVars[attr]
}
if (ogAttrRegex.test(val)) {
val = val.replace(ogAttrRegex, function (match, ogProp) {
if (settings.linkComponentFilter instanceof Function) {
var linkComponent = settings.linkComponentFilter(linkNode, ogProp)
if (linkComponent !== undefined && linkComponent !== null) {
return linkComponent
}
}
var meta = document.head.querySelector('meta[property="%og:prop%"]'.replace(ogAttrRegex, ogProp))
return meta ? meta.getAttribute('content') : ''
})
}
queryVars[attr] = encodeURIComponent(val)
})
linkNode.search = ''
var linkHref = linkNode.href.replace(/\?$/, '')
linkHref += '?' + (function () {
var query = []
for (var prop in queryVars) {
if (!queryVars.hasOwnProperty(prop)) {
continue
}
var value = queryVars[prop]
query.push(encodeURIComponent(prop) + '=' + value)
}
return query.join('&')
})()
linkNode.href = linkHref
return linkHref
}
}
var $ = window.jQuery || window.Zepto
if ($) {
$.fn.socialShare = function (method) {
if (methods[method]) {
return methods[method].apply(this.get(0), Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || !method) {
return methods.init.apply(this.get(0), arguments);
}
else {
$.error('Method ' + method + ' does not exist on jQuery.dateMiniChartControl');
}
}
}
return function socialShare(rootElements, options) {
if (!rootElements || rootElements.length === 0) {
return
}
if (rootElements instanceof Node) {
rootElements = [rootElements]
}
Array.prototype.forEach.call(rootElements, function (node) {
methods.init.call(node, options)
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment