2

I get my posts of an cpt like this: http://www.mywebsite.com/wp-json/wp/v2/cpt

at this posts there are shown post_meta values.

Does anyone know a way to order the posts by the meta like this: http://www.mywebsite.com/wp-json/wp/v2/cpt?orderby=my_meta_field

I found some solutions, but none of them are working for me…. Please help! Thanks! Stefan

0

2 Answers 2

2

You can use this filter to change order :

$type = "cptCode";

add_filter("rest_" . $type . "_query", function ($args, $query) {

    $args["orderby"] = "meta_value";
    $args["meta_key"] = "my_meta_field";

    return $args;

}, 10, 2);

You can also test $_GET to change the order conditionally.

1
  • thank you for your answer! This would be a nice one for me but it doesn´t work...after I copied this to funkctions.php and entered ".../v2/cpt?filter[orderby]=myfield" I dont get the solution...do I something wrong? :/
    – Treviz
    Commented Nov 2, 2017 at 13:41
1

Since wordpress 4.7, it has build in Rest Api 2. And since then there is no args like that. So you can write your own endopint and create what you want.

Check out answer: How to do a meta query using REST-API in WordPress 4.7+?

Or use: https://github.com/WP-API/rest-filter

1
  • thanks for your answer! The Plugin doesn´t work for me :/ I think I have to build my own controller class ...I thought there would exist a 3 line Code to activate these funkction :D
    – Treviz
    Commented Nov 2, 2017 at 13:39

Your Answer

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

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