Shopify Load More Posts Blog Code
Praxis worked with OLM designers to help load more posts in a Shopify blog. This is specific to the work on VaVaVoo, but may be helpful for additional stores and designs.
This document contains code and requires Shopify coding knowledge (liquid, css, JavaScript).
The following code snippets help you load more posts via Ajax to a Shopify blog.
Step 1
First, create a JavaSscript asset in Shopify's theme. I called it blog-loop.js. Here is the code to include:
var BlogLoop = {
current_page: 1,
init: function(){
this.bind_load_more();
},
show_loading: function(){
$('.blog-lm-label').hide();
$('.posts-ajax-loader').show();
},
hide_loading: function(){
$('.blog-lm-label').show();
$('.posts-ajax-loader').hide();
},
bind_load_more: function(){
var obj = this;
obj.current_page++;
$('.blog-lm-btn').click(function(){
// 21423300 blog id
var last_published_at = $( ".published_at" ).last().val();
var url = ws_url + '/get-more-blog-posts/'+last_published_at;
obj.show_loading();
$.ajax({
url: url,
method: "GET",
success: function(data){
obj.load_more(data);
obj.hide_loading();
}
});
return false;
});
},
load_more: function(data){
var cols = ['6','2','4','5','7']; //this is a design matter
data.articles.reverse();
data.articles.splice(0, 1);
for(var i in data.articles){
var html = '<div class="vlog-col col-md-{col}">' +
'<a href="{url}"><div class="box overlay black blog-image-home" style="background:url({img_url}); background-size:cover; height:300px; ">'+
'<h3>{title}</h3>'+
'<h3 class="read-more">READ MORE</h3>'+
' </div></a>' +
'</div>'+
'<input type="hidden" value="{published_at}" class="published_at" />';
var article_url = '/blog/news/' + data.articles[i].id;
html = html.replace('{url}', article_url);
html = html.replace('{col}', cols[i]);
html = html.replace('{title}', data.articles[i].title);
html = html.replace('{img_url}', data.articles[i].image.src);
html = html.replace('{published_at}', data.articles[i].published_at);
$('.blog-articles').append(html);
}
}
};
$(function(){
BlogLoop.init();
});
Step 2
Next, include the asset from inside your template or snippet:
{{ 'blog-loop.js' | asset_url | script_tag }}
The JavaScript code expects a <section> element with class 'blog-articles' to append the new ones there after the ajax loads. Also, it shows a loading wheel gif with class 'posts-ajax-loader'
Step 3
You need a php server on your side where you can call the Shopify app.
$url = 'https://'.$GLOBALS['api_key'].':'.$GLOBALS['pass'].'@'.'vavavoo.myshopify.com/admin/blogs/21423300/articles.json?limit=6&published_at_max='.urlencode($published_at_max);
$result = file_get_contents($url);
$published_at_max is the parameter passed when invoking this URL via GET (passed in the ajax call).
Step 4
You can get your blog id entering this url (Replace domain with yours):
https://vavavoo.myshopify.com/admin/blogs.json