Y
Y
Yury Bondaruk2021-09-11 16:43:56
RESTful API
Yury Bondaruk, 2021-09-11 16:43:56

How to add to wp-json sticky posts REST API request?

There is a link by which all posts on the page are obtained via GET: https://forblitz.ru/wp-json/wp/v2/posts
However, pinned posts are not displayed there at the beginning of the request. Can I get only separately sticky posts by https://forblitz.ru/wp-json/wp/v2/posts?sticky=true
can I somehow include sticky posts in the query of the first link by adding them to the beginning? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yury Bondaruk, 2021-09-11
@drnkwtr

Hey, descendants, if someday you ask the same question, then here is the solution for you (enter in functions.php)

function prefix_get_endpoint_phrase() {
    // rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.
    $url1 = 'https://forblitz.ru/wp-json/wp/v2/posts?sticky=true'; // path to your JSON file
  $url2 = 'https://forblitz.ru/wp-json/wp/v2/posts?per_page=30&categories_exclude=1'; // path to your JSON file
  $json1 = file_get_contents($url1);
  $json2 = file_get_contents($url2);

  $my_array1 = json_decode($json1, true);
  $my_array2 = json_decode($json2, true);
  $res = array_merge($my_array1, $my_array2);
    return $res;
}
 
/**
 * This function is where we register our routes for our example endpoint.
 */
function prefix_register_example_routes() {
    // register_rest_route() handles more arguments but we are going to stick to the basics for now.
    register_rest_route( 'wp/v1', '/posts', array(
        // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
        'methods'  => WP_REST_Server::READABLE,
        // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
        'callback' => 'prefix_get_endpoint_phrase',
    ) );
}
 
add_action( 'rest_api_init', 'prefix_register_example_routes' );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question