4

I am trying to display posts using the REST API and I want to display them in menu order based on how they are positioned in the admin menu.

I installed a plugin that allowed me to move posts to any position in the admin. I know querying the posts the normal way with wordpress there is a orderby: menu_order option, which would do what I am looking for, but I can't figure it out with the REST API.

My REST API looks like this:

https://example.com/wp-json/wp/v2/qd_leadership?_embed&per_page=100&orderby=menu_order

So I've tried that and that does not work. It says menu_order isn't an option. I also saw a post here:

Query WordPress (REST) posts by the order they appear on the admin

That had a similar question. The only answer on that post is to not have any orderby parameter and that should display them in the menu order, but that did not work for me. So I am stumped on how to order the posts from the REST API in menu order?

3 Answers 3

5

Its bug of wp core in rest api so you could use below hack for the solution.Please add below code in your active theme's function.php

add_filter( 'rest_post_collection_params', 'my_prefix_add_rest_orderby_params', 10, 1 );

function my_prefix_add_rest_orderby_params( $params ) {
    $params['orderby']['enum'][] = 'menu_order';

    return $params;
}

Tested and works.

0
2

Thanks to raju_eww for the hint in the right direction. But in case of a custom post type collection the filter hook name has to be like this:

add_filter( 'rest_custom-post-type_collection_params', 'my_prefix_add_rest_orderby_params', 10, 1 );
function my_prefix_add_rest_orderby_params( $params ) {
    $params['orderby']['enum'][] = 'menu_order';

    return $params;
}

found here: https://www.timrosswebdevelopment.com/wordpress-rest-api-post-order/

2
  • I used this code for product post type and did not work! rest_product_collection_params May 28, 2021 at 12:56
  • I used this code for product post type and did not work as default sort, but using orderby=menu_order query string it works. My filter hook is: rest_product_collection_params May 28, 2021 at 13:22
-1

Following code do sort by menu_order when orderby is not in query string (for woocommerce):

add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {
    if(!$_GET['orderby']) {
    $args['orderby'] = 'menu_order';
    $args['order'] = 'asc';
    }
    return $args;
    }

source

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.