Get the first 4 posts with a specific tag

Hello,

In my WordPress blog, the theme uses the “destacado” (featured) tag to feature the first 4 posts with this tag in the top section. I want to replicate this behavior in Frontity and I think I got it right but I want to make sure it is the correct way or if there’s a better form.

What I got so far in my component:

import React, {useEffect} from "react"
import { connect, styled } from "frontity"
import Link from "@frontity/components/link"

const IndexBody = ({state, actions}) => {
  useEffect(()=>{
    actions.source.fetch("/tag/destacado")
  }, []);
  const data = state.source.get("/tag/destacado")
  return (
    <>
      <DestaList isReady={data.isReady}>
        {data.isReady && data.items.map((item) => {
          const post = state.source[item.type][item.id]
          return (
            <Link key={item.id} link={post.link}>
              {post.title.rendered}
              <br/>
            </Link>
          )
        })}
      </DestaList>
    </>
  )
}

export default connect(IndexBody)

const DestaList = styled.div`
  height: 300px;
  background-color: ${(props) => (props.isReady ? "lightseagreen" : "maroon")};
`

The box starts with the maroon background, gets populated and turns light sea green, so I know the code works, but is it the best way?

Also, how can I just ask for the first 4 posts instead of the default 10?

Thanks!

Hi @eduardojoseperezf

Welcome to the Frontity Community!!

The actions.source.fetch() method doesn’t allow you to specify query parameters to the query.

You could use a low-level method to fetch the data from the WP REST API such as libraries.source.api.get() which will allow to specify parameters to the query

I think using the per_page=4 parameter for that query could be what you’re looking for

The thing about using this low-level method is that it doesn’t do all the automatic things that actions.source.fetch() do for you, so besides getting the data through libraries.source.api.get() you’ll have to manually populate the state with both:

  • An entry in state.source.data with information about that link.
  • Normalized entities in relevant part of the state, like state.source.post, state.source.category or state.source.author and so on.

Hope this helps