skip to Main Content

I need a push on a very precise subject. I have a fetch function to get results from a WordPress blog.

 function getTags() {

    let page = 1,
    tagURL = `https://css-tricks.com/wp-json/wp/v2/posts?_embed&per_page=4&tags=833&page=1`;
    console.log(tagURL)

    $loader.style.display = "block";
    fetch(tagURL)
    .then(response => response.json())
    .then(dataTag => {
        dataTag.map(dataTag => {

        // Content

    })
    .catch(err => {
        console.log(err);
        let message = err.statusText || "Es ist ein Fehler aufgetreten...";
        $posts.innerHTML = `<p>Error ${err.status}: ${message}</p>`;
        $loader.style.display = "none";
    });

 }

I need to create a pagination that shows 4 posts per page, but I can’t find the right way to do it.
If someone from the community can guide me, please, I would be very grateful.

Greetings and thanks.

<–UPDATE–>

the complete code is as follows

const
    $posts = document.getElementById('posts'),
    $loader = document.querySelector('.loader'),
    $template = document.getElementById("post-template").content


    function getTags() {
    let tagURL = `https://w-api.cyberconcept.de/wp-json/wp/v2/posts?_embed&per_page=2&tags=35&page=1`;
    $loader.style.display = "block";
    fetch(tagURL)
        .then(response => response.json())
        .then(dataTag => {
            dataTag.forEach(dataTag => {

                /**
                 * At this point a custom URL is created for each post-card element.
                 * @type {Element}
                 */
                const postLink = $template.querySelectorAll('.post-link');
                let url = window.location.origin + window.location.pathname;
                url = url + "?post_id=" + dataTag.id;

                postLink[0].setAttribute('href', url);
                postLink[1].setAttribute('href', url);
                /**
                 * Posts tags loop and post Tag url
                 * @type {string}
                 */
                let tags = "";
                const TagsUrl = window.location.origin + window.location.pathname
                dataTag._embedded["wp:term"][1].forEach(
                    dataTag => {
                        url = TagsUrl + "?tag_id=" + dataTag.id;
                        tags += `<a href="${url}" class="tag is-background-gradientDark">${dataTag.name}</a>`
                    }
                );

                /*
                 * Post images
                 */
                $template.querySelector('.post-image').src = dataTag._embedded["wp:featuredmedia"] ? dataTag._embedded["wp:featuredmedia"][0].source_url : "";
                $template.querySelector('.post-image').alt = dataTag._embedded["wp:featuredmedia"] ? dataTag._embedded["wp:featuredmedia"][0].alt_tex : "";
                $template.querySelector('.post-image').title = dataTag._embedded["wp:featuredmedia"] ? dataTag._embedded["wp:featuredmedia"][0].title.rendered : "";

                /*
                 * Post title
                 */
                $template.querySelector(".post-title").innerHTML = dataTag.title.rendered;
                /*
                 *Post Excerpt
                 */

                $template.querySelector('.post-excerpt').innerHTML = dataTag.excerpt.rendered;
                /*
                 *Post  Tags
                 */
                const tag = $template.querySelector('.post-tags');
                if (dataTag._embedded["wp:term"][1].length === 0) {
                    tag.style.display = "none";

                } else {
                    tag.style.display = "flex";
                    tag.innerHTML = ` ${tags}`;

                }

                let $clone = document.importNode($template, true);
                $posts.appendChild($clone);


            });
            $loader.style.display = "none";
        })
        .catch(err => {
            console.log(err);
            let message = err.statusText || "Es ist ein Fehler aufgetreten...";
            $posts.innerHTML = `<p>Error ${err.status}: ${message}</p>`;
            $loader.style.display = "none";
        });

      }
      
      document.addEventListener("DOMContentLoaded", () => {
   
        getTags(1);
   
})
<section id="blog-Slider" class="blog head-slider"></section>
<div class="container">
    <section id="posts-section">
        <h1 class="headline black-font"></h1>
        <div id="posts" class="blog grid"></div>
        <div id="pageNumber"></div>
    </section>
    <section id="single" class="blog single"></section>
</div>
<div id="pagination"></div>
<div class="blog loading">
    <img style="width: fit-content;" class="loader"
         src="" alt="laden...">
</div>

<template id="post-template">
    <div class="post-card">
        <a class="post-link">
            <img class="post-image">
        </a>
        <div>
            <div class="post-tags"></div>
            <a class="post-link">
                <h3 class="post-title"></h3>
                <p class="post-excerpt standard black-font"></p>
            </a>
        </div>
    </div>

</template>

2

Answers


  1. Try this :
    You need to increased page variable and call function getTags

    function getTags(page) {
    
    
    let tagURL = 'https://css-tricks.com/wp-json/wp/v2/posts?_embed&per_page=4&tags=833&page='+page;
    console.log(tagURL);
    
    $loader.style.display = "block";
    fetch(tagURL)
    .then(response => response.json())
    .then(dataTag => {
        dataTag.map(dataTag => {
    
        // Content
     
    
     
    
    })
    .catch(err => {
        console.log(err);
        let message = err.statusText || "Es ist ein Fehler aufgetreten...";
        $posts.innerHTML = `<p>Error ${err.status}: ${message}</p>`;
        $loader.style.display = "none";
    });
    
     }
    

    I have increaed variable value page after ajax response.

    Login or Signup to reply.
  2. you just need to rewrite the wrapper

    let totalPages = 0,
      pageNumber = document.querySelector('#pageNumber')
    getTags(1)
    
    function getTags(page) {
      let tagURL = `https://css-tricks.com/wp-json/wp/v2/posts?_embed&per_page=4&tags=833&page=${page}`;
      console.log(tagURL)
    
      //$loader.style.display = "block";
      fetch(tagURL)
        .then(async (response) => {
          let dataTag = await response.json() // get json
    
          totalPages = response.headers.get('x-wp-totalpages')
          if (!pageNumber.textContent) {
            createPage(); // create page number
          }
    
          // on response received, empty it
          document.querySelector('#content').innerHTML = '' 
          dataTag.forEach(data => { // not map
            document.querySelector('#content').innerHTML += `<li>${data.title.rendered}</<li>`
          })
    
        }).catch(err => {
          console.log(err);
          let message = err.statusText || "Es ist ein Fehler aufgetreten...";
          $posts.innerHTML = `<p>Error ${err.status}: ${message}</p>`;
          $loader.style.display = "none";
        });
    }
    
    function createPage() {
      for (var i = 0; i < totalPages; i++) {
    
        let li = document.createElement('li')
        li.textContent = i + 1
        li.onclick = function() {
          getTags(this.textContent)
        }
        pageNumber.appendChild(li)
      }
    }
    #pageNumber li{float: left;border: 1px solid #bbb;list-style: none;padding: 5px;cursor: pointer;}
    <div id="content"></div>
    <div id="pageNumber"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search