Documentação para Web Designers

Crie seus próprios layouts na Nuvem Shop

Postagens do Instagram

Esse tutorial te ensinará como configurar e vincular uma conta do Instagram com a sua loja. Isso permitirá exibir os últimos posts na página inicial.

Também é possível exibir 4, 8 ou 12 publicações em computadores, e 2, 4 ou 6 em celulares. Existe a possibilidade também exibir ou não a quantidade de "Likes" e "Comentários que existem no Instagram.

Para realizar esta configuração, você deverá seguir os seguintes passos:

1. Adicione o seguinte código em settings.txt, seguido de “Redes Sociais”.

Publicaciones de Instagram
    meta
        icon = instagram
        advanced = true
    subtitle
        subtitle = El Feed de Instagram muestra automáticamente tus últimas publicaciones en la página de inicio de tu tienda
    title
        title = Configurar cuenta de Instagram
    i18n_input
        name = instafeed_accesstoken
        description = Access Token (Necesario para validar tu cuenta)
    subtitle
        subtitle = <a target='_blank' href='https://ayuda.tiendanube.com/como-mostrar-mis-publicaciones-de-instagram-en-mi-tienda-nube'>¿Cómo obtener el Access Token?</a>
    checkbox
        name = show_instafeed
        description = Mostrar tus publicaciones de Instagram en la página de inicio de tu tienda
    title
        title = Imágenes en las publicaciones de Instagram
    subtitle
        subtitle = ¿Cuántas publicaciones querés mostrar?
    dropdown
        name = instafeed_qty
        values
            2 = 2 en celular y 4 en computadora
            4 = 4 en celular y 8 en computadora
            6 = 6 en celular y 12 en computadora
    checkbox
        name = instafeed_like
        description = Mostrar la cantidad de <em>‘Me gusta’</em> de cada publicación
    checkbox
        name = instafeed_comments
        description = Mostrar la cantidad de comentarios de cada publicación

2. Adicione as traduções em translations.txt:

es "Publicaciones de Instagram"
pt "Postagens do Instagram"
en "Instagram posts"


es "El Feed de Instagram muestra automáticamente tus últimas publicaciones en la página de inicio de tu tienda"
pt "O feed do Instagram exibe automaticamente suas últimas postagens na página inicial da sua loja."
en "Instagram Feed automatically shows your latest posts on the home page of your store"


es "Mostrar tus publicaciones de Instagram en la página de inicio de tu tienda"
pt "Exibir suas postagens do Instagram na página inicial da sua loja."
en "Show your Instagram posts on the home page of your store."


es "Configurar cuenta de Instagram"
pt "Configurar conta do Instagram"
en "Configure Instagram account"


es "<a target='_blank' href='https://ayuda.tiendanube.com/como-mostrar-mis-publicaciones-de-instagram-en-mi-tienda-nube'>¿Cómo obtener el Access Token?</a>"
pt "<a target='_blank' href='https://atendimento.nuvemshop.com.br/como-adicionar-o-feed-do-instagram'>Como obter o Access Token?</a>"
en "<a target='_blank' href='https://ayuda.tiendanube.com/como-mostrar-mis-publicaciones-de-instagram-en-mi-tienda-nube'>How to obtain the Access Token?</a>"


es "Access Token (Necesario para validar tu cuenta)"
pt "Access Token (Necessário para validar sua conta)"
en "Access Token (Necessary to validate your account)"


es "Imágenes en las publicaciones de Instagram"
pt "Imagens em posts do Instagram"
en "Images in Instagram posts"


es "¿Cuántas publicaciones querés mostrar?"
pt "Quantos posts você deseja exibir?"
en "How many posts do you want to show?"


es "2 en celular y 4 en computadora"
pt "2 no celular e 4 no computador"
en "2 in mobile and 4 in desktop"


es "4 en celular y 8 en computadora"
pt "4 no celular e 8 no computador"
en "4 in mobile and 8 in desktop"


es "6 en celular y 12 en computadora"
pt "6 no celular e 12 no computador"
en "6 in mobile and 12 in desktop"


es "Mostrar la cantidad de <em>‘Me gusta’</em> de cada publicación"
pt "Exibir quantidade de <em>“Likes”</em> de cada post"
en "Show the amount of <em>‘Likes’</ em> of each post"


es "Mostrar la cantidad de comentarios de cada publicación"
pt "Exibir quantidade de comentários de cada post"
en "Show the number of comments for each post"

3. Insira em layout.tpl, antes de fechar a tag </body>.

{% if template == 'home' and settings.show_instafeed %}
<script type="text/javascript">
    LS.ready.then(function(){
        $(document).ready(function(){

{# Instagram Feed #}

            {% if settings.show_instafeed %}
                var width = window.innerWidth;
                if (width > 767) {  
                    var feedqty = {{ settings.instafeed_qty * 2 }};
                } else {
                    var feedqty = {{ settings.instafeed_qty }};
                }
                {% set userid = settings.instafeed_accesstoken|split('.')|first %}


                {% set instlink = '{{link}}' %}
                {% set instimg = '{{image}}' %}
                {% set instlike = '{{likes}}' %}
                {% set instcomm = '{{comments}}' %}


                var userFeed = new Instafeed({
                get: 'user',
                    userId: '{{ userid }}',
                    accessToken: '{{ settings.instafeed_accesstoken }}',
                    resolution: 'standard_resolution',
                    template: '<div class="instafeed-item m-bottom-half"> <a href="{{instlink}}" class="instafeed-link" target="_blank"><div class="instafeed-img lazyload" data-bg="{{instimg}}"></div>{% if settings.instafeed_like or settings.instafeed_comments %}<div class="instafeed-info  font-small-extra">{% if settings.instafeed_like %}<span class="instafeed-info-item like"><i class="fa fa-heart"></i> {{instlike}}</span>{% endif %}{% if settings.instafeed_comments %}<span class="instafeed-info-item comments"><i class="fa fa-comment"></i> {{instcomm}}</span>{% endif %}</div>{% endif %}</a></div>',
                    limit: feedqty
               });
               userFeed.run();
           {% endif %}
     });
    });
</script>
{% endif %}

4. Incluir este código em  home.tpl, onde serão exibidas as publicações do Instagram.

{% if settings.show_instafeed  %}
    <div class="title-container row-fluid m-top m-bottom text-uppercase">
        {% set instuser = store.instagram|split('/')|last %}
        <div class="col-12 container-xs text-center">
            <h3 class="h5-xs">{% if store.instagram %}<a target="_blank" href="{{ store.instagram }}"><i class="fab fa-instagram"></i> @{{ instuser }}</a>{% else %}<i class="fab fa-instagram"></i> Instagram{% endif %}</h3>
        </div>
    </div>
<div class="instafeed-module m-bottom text-center">
    <div class="container">
        <div class="row-fluid">
            <div id="instafeed" class="overide-container-width m-none-xs">  
            </div>
        </div>
    </div>
</div>
{% endif %}

5. Adicionar o seguinte código ao final do arquivo snipplet/js/external.js.tpl.

{% if settings.show_instafeed and (template == 'home') %}
/*Instafeed*/
(function(){var e;e=function(){function e(e,t){var n,r;this.options={target:"instafeed",get:"popular",resolution:"thumbnail",sortBy:"none",links:!0,mock:!1,useHttp:!1};if(typeof e=="object")for(n in e)r=e[n],this.options[n]=r;this.context=t!=null?t:this,this.unique=this._genKey()}return e.prototype.hasNext=function(){return typeof this.context.nextUrl=="string"&&this.context.nextUrl.length>0},e.prototype.next=function(){return this.hasNext()?this.run(this.context.nextUrl):!1},e.prototype.run=function(t){var n,r,i;if(typeof this.options.clientId!="string"&&typeof this.options.accessToken!="string")throw new Error("Missing clientId or accessToken.");if(typeof this.options.accessToken!="string"&&typeof this.options.clientId!="string")throw new Error("Missing clientId or accessToken.");return this.options.before!=null&&typeof this.options.before=="function"&&this.options.before.call(this),typeof document!="undefined"&&document!==null&&(i=document.createElement("script"),i.id="instafeed-fetcher",i.src=t||this._buildUrl(),n=document.getElementsByTagName("head"),n[0].appendChild(i),r="instafeedCache"+this.unique,window[r]=new e(this.options,this),window[r].unique=this.unique),!0},e.prototype.parse=function(e){var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N,C,k,L,A,O,M,_,D;if(typeof e!="object"){if(this.options.error!=null&&typeof this.options.error=="function")return this.options.error.call(this,"Invalid JSON data"),!1;throw new Error("Invalid JSON response")}if(e.meta.code!==200){if(this.options.error!=null&&typeof this.options.error=="function")return this.options.error.call(this,e.meta.error_message),!1;throw new Error("Error from Instagram: "+e.meta.error_message)}if(e.data.length===0){if(this.options.error!=null&&typeof this.options.error=="function")return this.options.error.call(this,"No images were returned from Instagram"),!1;throw new Error("No images were returned from Instagram")}this.options.success!=null&&typeof this.options.success=="function"&&this.options.success.call(this,e),this.context.nextUrl="",e.pagination!=null&&(this.context.nextUrl=e.pagination.next_url);if(this.options.sortBy!=="none"){this.options.sortBy==="random"?M=["","random"]:M=this.options.sortBy.split("-"),O=M[0]==="least"?!0:!1;switch(M[1]){case"random":e.data.sort(function(){return.5-Math.random()});break;case"recent":e.data=this._sortBy(e.data,"created_time",O);break;case"liked":e.data=this._sortBy(e.data,"likes.count",O);break;case"commented":e.data=this._sortBy(e.data,"comments.count",O);break;default:throw new Error("Invalid option for sortBy: '"+this.options.sortBy+"'.")}}if(typeof document!="undefined"&&document!==null&&this.options.mock===!1){m=e.data,A=parseInt(this.options.limit,10),this.options.limit!=null&&m.length>A&&(m=m.slice(0,A)),u=document.createDocumentFragment(),this.options.filter!=null&&typeof this.options.filter=="function"&&(m=this._filter(m,this.options.filter));if(this.options.template!=null&&typeof this.options.template=="string"){f="",d="",w="",D=document.createElement("div");for(c=0,N=m.length;c<N;c++){h=m[c],p=h.images[this.options.resolution];if(typeof p!="object")throw o="No image found for resolution: "+this.options.resolution+".",new Error(o);E=p.width,y=p.height,b="square",E>y&&(b="landscape"),E<y&&(b="portrait"),v=p.url,l=window.location.protocol.indexOf("http")>=0,l&&!this.options.useHttp&&(v=v.replace(/https?:\/\//,"//")),d=this._makeTemplate(this.options.template,{model:h,id:h.id,link:h.link,type:h.type,image:v,width:E,height:y,orientation:b,caption:this._getObjectProperty(h,"caption.text"),likes:h.likes.count,comments:h.comments.count,location:this._getObjectProperty(h,"location.name")}),f+=d}D.innerHTML=f,i=[],r=0,n=D.childNodes.length;while(r<n)i.push(D.childNodes[r]),r+=1;for(x=0,C=i.length;x<C;x++)L=i[x],u.appendChild(L)}else for(T=0,k=m.length;T<k;T++){h=m[T],g=document.createElement("img"),p=h.images[this.options.resolution];if(typeof p!="object")throw o="No image found for resolution: "+this.options.resolution+".",new Error(o);v=p.url,l=window.location.protocol.indexOf("http")>=0,l&&!this.options.useHttp&&(v=v.replace(/https?:\/\//,"//")),g.src=v,this.options.links===!0?(t=document.createElement("a"),t.href=h.link,t.appendChild(g),u.appendChild(t)):u.appendChild(g)}_=this.options.target,typeof _=="string"&&(_=document.getElementById(_));if(_==null)throw o='No element with id="'+this.options.target+'" on page.',new Error(o);_.appendChild(u),a=document.getElementsByTagName("head")[0],a.removeChild(document.getElementById("instafeed-fetcher")),S="instafeedCache"+this.unique,window[S]=void 0;try{delete window[S]}catch(P){s=P}}return this.options.after!=null&&typeof this.options.after=="function"&&this.options.after.call(this),!0},e.prototype._buildUrl=function(){var e,t,n;e="https://api.instagram.com/v1";switch(this.options.get){case"popular":t="media/popular";break;case"tagged":if(!this.options.tagName)throw new Error("No tag name specified. Use the 'tagName' option.");t="tags/"+this.options.tagName+"/media/recent";break;case"location":if(!this.options.locationId)throw new Error("No location specified. Use the 'locationId' option.");t="locations/"+this.options.locationId+"/media/recent";break;case"user":if(!this.options.userId)throw new Error("No user specified. Use the 'userId' option.");t="users/"+this.options.userId+"/media/recent";break;default:throw new Error("Invalid option for get: '"+this.options.get+"'.")}return n=e+"/"+t,this.options.accessToken!=null?n+="?access_token="+this.options.accessToken:n+="?client_id="+this.options.clientId,this.options.limit!=null&&(n+="&count="+this.options.limit),n+="&callback=instafeedCache"+this.unique+".parse",n},e.prototype._genKey=function(){var e;return e=function(){return((1+Math.random())*65536|0).toString(16).substring(1)},""+e()+e()+e()+e()},e.prototype._makeTemplate=function(e,t){var n,r,i,s,o;{% raw %}r=/(?:\{{2})([\w\[\]\.]+)(?:\}{2})/,{% endraw %} n=e;while(r.test(n))s=n.match(r)[1],o=(i=this._getObjectProperty(t,s))!=null?i:"",n=n.replace(r,function(){return""+o});return n},e.prototype._getObjectProperty=function(e,t){var n,r;t=t.replace(/\[(\w+)\]/g,".$1"),r=t.split(".");while(r.length){n=r.shift();if(!(e!=null&&n in e))return null;e=e[n]}return e},e.prototype._sortBy=function(e,t,n){var r;return r=function(e,r){var i,s;return i=this._getObjectProperty(e,t),s=this._getObjectProperty(r,t),n?i>s?1:-1:i<s?1:-1},e.sort(r.bind(this)),e},e.prototype._filter=function(e,t){var n,r,i,s,o;n=[],r=function(e){if(t(e))return n.push(e)};for(i=0,o=e.length;i<o;i++)s=e[i],r(s);return n},e}(),function(e,t){return typeof define=="function"&&define.amd?define([],t):typeof module=="object"&&module.exports?module.exports=t():e.Instafeed=t()}(this,function(){return e})}).call(this);
{% endif %}

6. Colocar o Lazyload para imagens de fundo em static/js/external-no-dependencies.js.  

/* lazysizes extension to more HTML elements */
!function(a,b){var c=function(){b(a.lazySizes),a.removeEventListener("lazyunveilread",c,!0)};b=b.bind(null,a,a.document),"object"==typeof module&&module.exports?b(require("lazysizes")):a.lazySizes?c():a.addEventListener("lazyunveilread",c,!0)}(window,function(a,b,c){"use strict";function d(a,c){if(!g[a]){var d=b.createElement(c?"link":"script"),e=b.getElementsByTagName("script")[0];c?(d.rel="stylesheet",d.href=a):d.src=a,g[a]=!0,g[d.src||d.href]=!0,e.parentNode.insertBefore(d,e)}}var e,f,g={};b.addEventListener&&(f=/\(|\)|\s|'/,e=function(a,c){var d=b.createElement("img");d.onload=function(){d.onload=null,d.onerror=null,d=null,c()},d.onerror=d.onload,d.src=a,d&&d.complete&&d.onload&&d.onload()},addEventListener("lazybeforeunveil",function(a){if(a.detail.instance==c){var b,g,h,i;a.defaultPrevented||("none"==a.target.preload&&(a.target.preload="auto"),b=a.target.getAttribute("data-link"),b&&d(b,!0),b=a.target.getAttribute("data-script"),b&&d(b),b=a.target.getAttribute("data-require"),b&&(c.cfg.requireJs?c.cfg.requireJs([b]):d(b)),h=a.target.getAttribute("data-bg"),h&&(a.detail.firesLoad=!0,g=function(){a.target.style.backgroundImage="url("+(f.test(h)?JSON.stringify(h):h)+")",a.detail.firesLoad=!1,c.fire(a.target,"_lazyloaded",{},!0,!0)},e(h,g)),i=a.target.getAttribute("data-poster"),i&&(a.detail.firesLoad=!0,g=function(){a.target.poster=i,a.detail.firesLoad=!1,c.fire(a.target,"_lazyloaded",{},!0,!0)},e(i,g)))}},!1))});

7. Então, no seu arquivo SASS, (por exemplo: para o layout Trend, este é chamado de main-color.scss.tpl), você deverá adicionar os seguintes estilos:

Esclarecimento: Lembre-se de adaptar as variáveis de cor de acordo com o seu layout.

.instafeed-module {
    .instafeed-item {
        display: inline-block;
        .instafeed-img {
            overflow: hidden;
            position: relative;
            margin: 10px;
            padding-top: 100%;            
            background-position: center center;
            background-size: cover;
        }
        .instafeed-info {
            text-align: left;
             .instafeed-info-item {
                display: inline-block;
                margin-left: 10px;
                color: $main-foreground;
            }
        }
    }
}

8. Por último, em seu arquivo style.css, você deverá adicionar os seguintes estilos: 

.instafeed-module .instafeed-item {
    width:25%!important;
}

@media (max-width: 767px) {
    .instafeed-module .instafeed-item {
         width:50%!important;
    }
}

8. Pronto! A loja já estará vinculada para exibir as postagens do Instagram.