-1

When I want to get the posts from my Wordpress Rest API, the sticky posts are not at the top, but are sorted by date like the others.

When I try to sort by sticky

wp-json/wp/v2/posts?orderby=sticky

I get this error message:

code: "rest_invalid_param",
message: "Invalid parameter(s): orderby",

If I append the following parameters instead

wp-json/wp/v2/posts?ignore_sticky_posts=0

or

wp-json/wp/v2/posts?ignore_sticky_posts=1

the sorting does not change.

How can I make the sticky posts always be at the top?

3
  • you can retrieve sticky posts with the endpoint wp/v2/posts/?sticky=true. Commented Oct 10, 2024 at 20:41
  • Thanks, but I already know that. But I need the full list, with the sticky posts on top. Do I really have to get the sticky post and the non-sticky posts separately and then combine, and not simply by ordering all posts so that the sticky ones are on top? Commented Oct 11, 2024 at 10:08
  • if you don't want to combine that on client side with the answer of Webpress, you can create a new endpoint on the api : developer.wordpress.org/rest-api Commented Oct 11, 2024 at 13:56

1 Answer 1

1

In the WordPress REST API, there's no built-in parameter to sort posts by sticky status directly. However, you can achieve your goal by fetching the sticky posts and non-sticky posts separately and then combining them in your application.

Fetch Sticky Posts: Use the endpoint to get only sticky posts:

wp-json/wp/v2/posts?sticky=true

Fetch Non-Sticky Posts: Use the endpoint to get non-sticky posts:

wp-json/wp/v2/posts?ignore_sticky_posts=1

Combine Results: After retrieving both sets of posts, combine the sticky posts with the non-sticky ones in your application logic.

async function fetchPosts() {
const stickyPostsResponse = await fetch('wp-json/wp/v2/posts?sticky=true');
const stickyPosts = await stickyPostsResponse.json();

const nonStickyPostsResponse = await fetch('wp-json/wp/v2/posts?ignore_sticky_posts=1');
const nonStickyPosts = await nonStickyPostsResponse.json();

const allPosts = [...stickyPosts, ...nonStickyPosts];
return allPosts;

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.