Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wihodges/28b415bab370097f97cdab9cc0d5eac6 to your computer and use it in GitHub Desktop.
Save wihodges/28b415bab370097f97cdab9cc0d5eac6 to your computer and use it in GitHub Desktop.
I need a simple way to load more post to a news section in Craft CMS.
$('#loadMorePosts').click(function() {
loadMorePosts();
});
function loadMorePosts() {
var data = {
'CSRF': $('input[name="CRAFT_CSRF_TOKEN"]').val(),
};
$.ajax({
'type': 'get',
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
'cache': false,
'data': data,
'url': 'news.json',
'dataType': 'json',
'timeout': 50000,
'success': function(data) {
console.log('data');
//Iterate the data
$.each(data, function(i, newdata) {
//But we need the nested object, probably a better way to do this...
$.each(newdata, function(i, val) {
var html = "<a class=\"news-card\" href=\"" +
val.url + "\"><span class=\"date\">" + val.date_published + "</span><span class=\"title\">" + val.title + "</span></a>";
$(html).appendTo('#js-newsLoadcontainer');
});
});
} //end of success
}).done(function(response) {
console.log(response);
}).fail(function(error) {
// Total fail.
});
}
<?php
use craft\elements\Entry;
use craft\helpers\UrlHelper;
return [
'endpoints' => [
'news.json' => function() {
return [
'elementType' => Entry::class,
'elementsPerPage' => 3,
'pageParam' => 'pg',
'criteria' => ['section' => 'news'],
'transformer' => function(Entry $entry) {
return [
'title' => $entry->title,
'url' => $entry->url,
'date_published' => $entry->postDate->format(\DateTime::ATOM),
'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
];
},
];
}
]
];
<div id="js-newsLoadcontainer">
{% set entriesList = craft.entries.section('news').limit(3) %}
{% for entries in entriesList %}
<a class="post" href=" {{ entries.url }} ">
<span class="date">{{ entry.postDate | date("M d, Y") }}</span>
<span class="title">{{ entries.title }}</span>
</a>
{% endfor %}
</div>
<a id="loadMorePosts">Load More</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment