<p>Following up on previous questions of mine: <a href="https://craftcms.stackexchange.com/questions/35754/how-to-use-multiple-different-instances-element-api-load-more-button/35762#35762">How to use multiple different instances Element API &quot;Load More&quot; button?</a></p>
<p>I have a website that utilizes the &quot;load More&quot; (button) method shown here: <a href="http://craftsnippets.com/articles/infinite-scrolling-and-lazy-loading-with-craft-cms" rel="nofollow noreferrer">http://craftsnippets.com/articles/infinite-scrolling-and-lazy-loading-with-craft-cms</a></p>
<p>How can I load more entries of a category on that category's page? Currently when I add <code>.relatedTo(category)</code> to the loop on the category page, it works sorta, but it will also load all the rest of the entries after it's gone through the entries of that category. I only want it to load the entries of the category.</p>
<p><strong>Also:</strong> Same thing as my last question (linked above) I need this to be used independently of other instances. Martin Spain's <a href="https://craftcms.stackexchange.com/a/35762/10770">answer</a> addressed this in my last question, and worked perfectly. I just don't if/how I can implement it for categories.</p>
<p><strong>element-api.php</strong></p>
<pre><code>&lt;?php

use Craft;
use craft\elements\Entry;
use League\Fractal\TransformerAbstract;
use craft\web\View;

class TwigTransformer extends TransformerAbstract
{

    public function __construct($settings)
    {
        $this-&gt;settings = $settings;
    }

    public function transform( $entry )
    {
        $oldMode = Craft::$app-&gt;view-&gt;getTemplateMode();
        Craft::$app-&gt;view-&gt;setTemplateMode(View::TEMPLATE_MODE_SITE);
        $html = Craft::$app-&gt;view-&gt;renderTemplate( $this-&gt;settings['templatePath'], [$this-&gt;settings['variableName'] =&gt; $entry]);
        Craft::$app-&gt;view-&gt;setTemplateMode($oldMode);

        return [
            'id' =&gt; $entry-&gt;id,
            'html' =&gt; $html
        ];
    }
}

return [
    'endpoints' =&gt; [
        'lazy-load' =&gt; function() {

        // validate and decode settings
        $hashed_settings = Craft::$app-&gt;request-&gt;getParam('settings');
        $settings = [];

        foreach ($hashed_settings as $key =&gt; $value) {
            $value = Craft::$app-&gt;security-&gt;validateData($value);
            if($value === false){
                return false;
            }else{
                $settings[$key] = $value;
            }
        }

        // criteria
        $skipEntries = Craft::$app-&gt;request-&gt;getParam('skip') ?? 0;
        $criteria = [
            'section' =&gt; $settings['section'], 
            'limit' =&gt;  $settings['limit'],
            'offset' =&gt;  $settings['limit'] * Craft::$app-&gt;request-&gt;getParam('offset') + $skipEntries,
            'order' =&gt; $settings['orderBy'],
        ];
      
        return [
            'elementType' =&gt; Entry::class,
            'criteria' =&gt; $criteria,
            'paginate' =&gt; true,
            'transformer' =&gt; new TwigTransformer($settings),
        ];
        },
    ]
];
</code></pre>
<p><strong>_category.twig</strong></p>
<pre><code>&lt;section&gt;
            {# settings #}
            {% set element_api_url = 'lazy-load' %}
            {% set settings = {
                section: 'aBetterPost',
                variableName: 'article',
                templatePath: '_layouts/_post.twig',
                orderBy: 'postDate DESC',
                limit: 6,
            } %}

            {# hashed settings #}
            {% set hashed_settings = [] %}
            {% for key, setting in settings %}
               {% set hashed_settings = hashed_settings|merge({(key): setting|hash}) %}
            {% endfor %}

            {# initial content #}
            {# initial content #}
            &lt;div class=&quot;js-lazy-wrapper&quot;&gt;
                &lt;div class=&quot;more-posts-section&quot;&gt;
                    &lt;div class=&quot;section-header&quot;&gt;
                        &lt;h2&gt;More Posts in &lt;span&gt;{{ category.title }}&lt;/span&gt;&lt;/h2&gt;
                    &lt;/div&gt;
                    
                    &lt;div class=&quot;more-posts-wrap-border&quot;&gt;
                        &lt;div class=&quot;more-posts-wrap js-lazy-list&quot;&gt;
                            {% for page in craft.entries.section(settings.section).orderBy(settings.orderBy).relatedTo(category).limit(settings.limit).all() %}
                              {% include settings.templatePath with {(settings.variableName): page} %}
                            {% endfor %}
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div class=&quot;load-button-wrap&quot;&gt;
                        &lt;button class=&quot;js-load-more load-button&quot;&gt;{{'load more'|t}}&lt;/button&gt;
                    &lt;/div&gt;

                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/section&gt;

        


        {# ajax request #}
        {% js %}
        // twig to js
        var lazy_settings = {{hashed_settings|json_encode|raw}};
        var element_api_url = '{{url(element_api_url)}}';

        //variables
        var lazy_offset = 1
        var current_request = null;

        //html elements
        var lazy_wrapper = $('.js-lazy-wrapper');
        var lazy_button = lazy_wrapper.find('.js-load-more');
        var lazy_list = lazy_wrapper.find('.js-lazy-list');

        lazy_button.on('click', function(){
          if (current_request == null){

            current_request = $.ajax({
              url: element_api_url,
              method: 'GET',
              data: {
                skip: 0,
                offset: lazy_offset,
                settings: lazy_settings,
              },
              beforeSend: function(){
                lazy_button.addClass('is-loading');
              },        
            }).always(function(returned) {
                lazy_button.removeClass('is-loading');
                current_request = null;
            }).done(function(returned) {
              lazy_offset ++
              var html = ''
              $.each(returned.data, function(index, article){
                html += article.html
              })
              lazy_list.append(html)
              if(returned.data.length == 0){
                lazy_button.hide();
              }
            }).fail(function(data){
              alert('error');
            })
          }
        });
        {% endjs %}

</code></pre>

CC BY-SA 4.0
2020-07-14T10:57:35.220Z
Can you add the code that you currently have?
dmatthams
CC BY-SA 4.0
2020-07-15T03:13:34.880Z
@user3788089 Code added.
Justin Kendall
<craft3><php><plugin-elementapi><javascript>
How to load more entries of a category on that category's page with Element API?
# How to load more entries of a category on that category's page with Element API?

(Asked by: username_0 on 2020-07-13)

Following up on previous questions of mine: How to use multiple different instances Element API "Load More" button?
I have a website that utilizes the "load More" (button) method shown here: http://craftsnippets.com/articles/infinite-scrolling-and-lazy-loading-with-craft-cms
How can I load more entries of a category on that category's page? Currently when I add .relatedTo(category) to the loop on the category page, it works sorta, but it will also load all the rest of the entries after it's gone through the entries of that category. I only want it to load the entries of the category.
Also: Same thing as my last question (linked above) I need this to be used independently of other instances. Martin Spain's answer addressed this in my last question, and worked perfectly. I just don't if/how I can implement it for categories.
element-api.php
settings = $settings;
    }

    public function transform( $entry )
    {
        $oldMode = Craft::$app->view->getTemplateMode();
        Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_SITE);
        $html = Craft::$app->view->renderTemplate( $this->settings['templatePath'], [$this->settings['variableName'] => $entry]);
        Craft::$app->view->setTemplateMode($oldMode);

        return [
            'id' => $entry->id,
            'html' => $html
        ];
    }
}

return [
    'endpoints' => [
        'lazy-load' => function() {

        // validate and decode settings
        $hashed_settings = Craft::$app->request->getParam('settings');
        $settings = [];

        foreach ($hashed_settings as $key => $value) {
            $value = Craft::$app->security->validateData($value);
            if($value === false){
                return false;
            }else{
                $settings[$key] = $value;
            }
        }

        // criteria
        $skipEntries = Craft::$app->request->getParam('skip') ?? 0;
        $criteria = [
            'section' => $settings['section'], 
            'limit' =>  $settings['limit'],
            'offset' =>  $settings['limit'] * Craft::$app->request->getParam('offset') + $skipEntries,
            'order' => $settings['orderBy'],
        ];
      
        return [
            'elementType' => Entry::class,
            'criteria' => $criteria,
            'paginate' => true,
            'transformer' => new TwigTransformer($settings),
        ];
        },
    ]
];

_category.twig

            {# settings #}
            {% set element_api_url = 'lazy-load' %}
            {% set settings = {
                section: 'aBetterPost',
                variableName: 'article',
                templatePath: '_layouts/_post.twig',
                orderBy: 'postDate DESC',
                limit: 6,
            } %}

            {# hashed settings #}
            {% set hashed_settings = [] %}
            {% for key, setting in settings %}
               {% set hashed_settings = hashed_settings|merge({(key): setting|hash}) %}
            {% endfor %}

            {# initial content #}
            {# initial content #}
            
                
                    
                        More Posts in {{ category.title }}
                    
                    
                    
                        
                            {% for page in craft.entries.section(settings.section).orderBy(settings.orderBy).relatedTo(category).limit(settings.limit).all() %}
                              {% include settings.templatePath with {(settings.variableName): page} %}
                            {% endfor %}
                        
                    
                    
                    
                        {{'load more'|t}}
                    

                
            
        

        


        {# ajax request #}
        {% js %}
        // twig to js
        var lazy_settings = {{hashed_settings|json_encode|raw}};
        var element_api_url = '{{url(element_api_url)}}';

        //variables
        var lazy_offset = 1
        var current_request = null;

        //html elements
        var lazy_wrapper = $('.js-lazy-wrapper');
        var lazy_button = lazy_wrapper.find('.js-load-more');
        var lazy_list = lazy_wrapper.find('.js-lazy-list');

        lazy_button.on('click', function(){
          if (current_request == null){

            current_request = $.ajax({
              url: element_api_url,
              method: 'GET',
              data: {
                skip: 0,
                offset: lazy_offset,
                settings: lazy_settings,
              },
              beforeSend: function(){
                lazy_button.addClass('is-loading');
              },        
            }).always(function(returned) {
                lazy_button.removeClass('is-loading');
                current_request = null;
            }).done(function(returned) {
              lazy_offset ++
              var html = ''
              $.each(returned.data, function(index, article){
                html += article.html
              })
              lazy_list.append(html)
              if(returned.data.length == 0){
                lazy_button.hide();
              }
            }).fail(function(data){
              alert('error');
            })
          }
        });
        {% endjs %}

**Tags:** craft3, php, plugin-elementapi, javascript

> **Comments:**
> **username_1**: Can you add the code that you currently have?  
> **username_0**: @user3788089 Code added.  

---

## 0 answers

