Share links | Developerdesks

Php share facebook twitter

This widget will show a Facebook «like» button and «comments» box together with «tweet» button and «google plusone» button on your page.

 class SimpleShare extends CWidget < /** * Site Name * @var string * defaults to Yii::app()->name */ public $siteName = ''; /** * Site Administrator's Facebook ID * @var string */ public $fbSiteAdmin = 'XXXXXXXXXXXXXX'; /** * URL of the page * @var string * defaults to the current page URL */ public $pageUrl = ''; /** * Title of the page * @var string */ public $pageTitle = ''; /** * Type of the Page : eg. website, article, . etc. * @var string * defaults to 'article' */ public $pageType = ''; /** * Description of the page * @var string */ public $pageDescription = ''; /** * Image(s) of the page * @var mixed * can be a single string or array of strings * defaults $this->defaultPageImage */ public $pageImages = ''; /** * Default image of the page * @var string */ public $defaultPageImage = '/images/fb/site-logo.jpg'; /** * Show Comments * @var boolean * defaults to true */ public $showComments = true; /** * Minimum IE version required * @var string */ public $minimumIEVersion = '8'; /** * Initialization * @see CWidget::init() */ public function init() < parent::init(); // Site Name if ($this->siteName == '') < $this->siteName = Yii::app()->name; > // base URL $baseUrl = Yii::app()->request->hostInfo . Yii::app()->request->baseUrl; // URL of the page if ($this->pageUrl == '') < $this->pageUrl = $baseUrl . '/' . Yii::app()->request->pathInfo; > // Type of the page if ($this->pageType == '') < $this->pageType = 'article'; > // Set opengraph meta tags /** @var CClientScript $cs */ $cs = Yii::app()->getClientScript(); $cs->registerMetaTag($this->siteName, NULL, NULL, array('property'=>'og:site_name')); $cs->registerMetaTag($this->fbSiteAdmin, NULL, NULL, array('property'=>'fb:admins')); $cs->registerMetaTag($this->pageUrl, NULL, NULL, array('property' =>'og:url')); $cs->registerMetaTag($this->pageTitle, NULL, NULL, array('property'=>'og:title')); $cs->registerMetaTag($this->pageType, NULL, NULL, array('property'=>'og:type')); // Description of the page if ($this->pageDescription != "") < $cs->registerMetaTag($this->pageDescription, NULL, NULL, array('property'=>'og:description')); > // Image(s) of the page if (is_array($this->pageImages)) < if (count($this->pageImages) == 0) < $this->pageImages = $this->defaultPageImage; > foreach($this->pageImages as $image) < $cs->registerMetaTag($baseUrl . $image, NULL, NULL, array('property'=> 'og:image')); > > else < if ($this->pageImages == "") < $this->pageImages = $this->defaultPageImage; > $cs->registerMetaTag($baseUrl . $this->pageImages, NULL, NULL, array('property'=> 'og:image')); > // javasctipt to enable the gadgets $init_js = var msie = navigator.appVersion.toLowerCase(); msie = (msie.indexOf('msie')>-1) ? parseInt(msie.replace(/.*msie[ ]/,'').match(/^[0-9]+/)) : 0; if (msie == 0 || msie >= $this->minimumIEVersion) < $('#sns-share').show(); // google plus one window.___gcfg = < lang: 'ja' >; (function() < var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); >)(); // twitter !function(d,s,id)< var js,fjs=d.getElementsByTagName(s)[0], p=/^http:/.test(d.location)?'http':'https'; if(!d.getElementById(id))< js=d.createElement(s); js.id=id; js.async=true; js.src=p+'://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js,fjs); > >(document, 'script', 'twitter-wjs'); // facebook (function(d, s, id) < var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.async=true; js.src = "//connect.facebook.net/ja_JP/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); >(document, 'script', 'facebook-jssdk')); > INIT_JS; $cs->registerScript('init-sns-share', $init_js, CClientScript::POS_READY); > /** * Display the widget * @see CWidget::run() */ public function run() < echo '
' . "\n"; echo '

Share the page with Facebook, twitter and google plusone

'
. "\n"; echo '
' . "\n"; // google plusone echo '
' . "\n"; echo '$this->pageUrl . '">' . "\n"; echo '
'
. "\n"; // twitter $tw_text = $this->siteName . ' - ' . $this->pageTitle; if ( $this->pageDescription != '') < $tw_text .= ' : ' . $this->pageDescription; > echo '
' . "\n"; echo ' . 'class="twitter-share-button" ' . 'data-url hljs-keyword">$this->pageUrl . '" ' . 'data-text hljs-string">'" ' . 'data-count="horizontal">Tweet' . "\n"; echo '
'
. "\n"; // facebook echo '
. 'data-href hljs-keyword">$this->pageUrl . '" ' . 'data-send="true" ' . 'data-width="500" ' . 'data-show-faces="false">
'
. "\n"; if ($this->showComments) < echo '
'
. "\n"; echo '
' . "\n"; echo '
. 'data-href hljs-keyword">$this->pageUrl . '" ' . 'data-num-posts="4" ' . 'data-width="600">
'
. "\n"; > echo '
'
. "\n"; echo '
'
. "\n"; > >

Usage ¶

You can put the widget anywhere in your view like the following.

 $this->widget('SimpleShare', array( 'pageTitle' => 'The title of the page.', 'pageDescription' => 'The long descriptions of the page.', 'pageType' => 'article', 'pageImages' => array('/images/001.jpg', '/images/002.jpg'), )); ?> 

‘pageImages’ can be an array of strings (up to 5 images).

You may want to use the default values for ‘pageType’ and ‘pageImages’.

 $this->widget('SimpleShare', array( 'pageTitle' => 'The title of the page.', 'pageDescription' => 'The long descriptions of the page.', )); ?> 

Notice ¶

This is a kind of quick and dirty code just to satisfy the specific needs of mine. But I hope it will show the basic know-hows to implement those gadgets in an yii-powered site.

You may want to customize the widget according to your needs, or want to make it much more flexible and generic.

And also you would like to give some tries to these extensions.

Источник

Кнопки «Поделиться», «Tweet» и «Share» с собственным дизайном

Начну с того, что дизайн — не единственная причина, по которой следует использовать собственные кнопки социальных сетей. О причинах написано в отдельном посту, поэтому сейчас в это углубляться не будем.

Рассмотрим создание кнопки для каждого социального сервиса по-отдельности. В качестве тестируемой страницы у нас будет стандартный пост WordPress — «Привет, мир!».

Twitter

Начнём с несложного примера:

Текст и URL — два основных параметра, конечно, их вполне достаточно для создания кнопки, хэштеги например можно спокойно добавлять в переменную $text, тем не менее давайте рассмотрим полный список параметров:

url Абсолютный URL с HTTP или HTTPS, будет автоматически сокращён через t.co. Также рекомендуется пропускать его через php-функцию urlencode() . text Текст твита. Должен быть в кодировке UTF-8 и состоять не более чем из 140 символов (с учётом ссылки и хэштегов!). После нажатия на кнопку «Твитнуть» у пользователя будет возможность отредактировать этот текст — также имейте это ввиду. hashtags Список #хэштегов через запятую без символа «#». via Через что был опубликован твит? Информация будет добавлена в конце твита. Например с помощью @twitterfeed. В передаваемом параметру значении символ «@» указывать не нужно. in_reply_to Ответ на другой твит. В качестве значения параметра нужно указать ID твита, на который нужно ответить. Имя автора, на чей твит мы хотим написать ответ, будет автоматически добавлено в начало твита. related Укажите через запятую аккаунты в Твиттере, которые будет автоматически рекомендовано зафолловить пользователю после того, как он запостит твит.

Раньше я использовал php-функцию для преобразования ссылок через bit.ly, но это значительно тормозило скорость загрузки страниц и я решил не сокращать ссылки на своём блоге.

Язык во всплывающем окошке будет таким же, как в профиле посетителя вашего сайта в твиттере.
Ещё один пример:

При нажатии на кнопку «Твитнуть» получаем следующее:

Поделиться ссылкой в Твиттере

Facebook

p[title] Заголовок поста. p[summary] Анонс поста. p[url] Ссылка на пост. Не забываем про функцию urlencode() . p[images][0] Основное изображение поста, вы также можете перечислить дополнительные изображения в параметрах p[images][1] , p[images][2] и так далее. Хотел бы заметить, что если вы защищаете изображения от хотлинков через .htaccess, то надо будет добавить все эти социальные сети в исключения, иначе ваши картинки просто не будут отображаться.

Поделиться ссылкой на Фейсбук

Вконтакте

Все параметры абсолютно аналогичны параметрам из примера про кнопку Facebook, поэтому не буду их описывать лишний раз. А в результате получаем вот что:

Сохранить в Вконтакте

Ну вот и всё, теперь при помощи CSS вы можете придать ссылкам какой угодно вид (например как у меня на блоге).

Смотрите также

Миша

Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.

Пишите, если нужна помощь с сайтом или разработка с нуля.

Источник

Share Your Website Post To Social Media using php

Developer Desks Developer Desks

Share your website post to social media using php. Everyone want to share their post in social media regularly to get increase the page views and also website view. So the social media is the best way to promote our content to reach everyone. When ever we write our post we directly update this post into our social media using php

Here I am written sharing code, Just click social media icons it will share automatically to your social media timeline

Here I have get our website details description and content using php

Here we going to add Facebook and Google plus sharing

     
>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">

Add Javascript for sharing link
Het your facebook api id from the developers facebook page

   

Here we added the javascript for post article. now you can used ur post to share in social media

Источник

how to Social Media Sharing Buttons in php

social-media-button-php

In Social Media Sharing Buttons in php Post we will show you how to share your page or website in Social Media Sharing Buttons using php. This post we will share ,link on social media with title and url using php.

we will share Buffer, diggit, Email, Facebook, Google+, LinkedIn, Pinterest, Print, Reddit, StumbleUpon, Tumblr, Twitter, vkontakte and Yummly social media with php code.

For use this code of share button on social media, we have to pass url and title of url and pass in to give method of social media tab.

For use this code pass your site url and title in given variable $site_url and $site_title .

Social Media Sharing Buttons using php

How to Set thumbnail like, title, description

Pass your url and title in variable

  
&text=" target="_blank"> " target="_blank">

Conclusion for how to Social Media Sharing Buttons in php

Hope this code and post will help you implement how to Social Media Sharing Buttons in PHP. if you need any help or any feedback give it in the comment section or you have a good idea about this post you can give it in the comment section. Your comment will help us to help you more and improve us.

Источник

Читайте также:  Python list read only one
Оцените статью