skip to Main Content

Using WordPress REST API, I’m externally getting posts:
https://example.com/wp-json/wp/v2/posts?orderby=date&order=desc&per_page=12

Body results:

[
    {
        "date": "2022-05-05T12:12:12",
        "link": "https://example.com/blog/132/",
        "title": {
            "rendered": "F: Title"
        }
    },
    {
        "date": "2022-04-04T12:12:12",
        "link": "https://example.com/blog/434/",
        "title": {
            "rendered": "E: Title"
        }
    },
    {
        "date": "2022-03-03T12:12:12",
        "link": "https://example.com/blog/324/",
        "title": {
            "rendered": "A: Title"
        }
    },
    etc...

]

I’d like to sort title by alphabetical order.

What would be the best solution?

I’m unable to use WP_Query since the posts are being pulled from an external WP API source.

2

Answers


  1. May be something like that :

    <?php
    function cmp($a, $b)
    {
        if ($a['title']['rendered'] == $b['title']['rendered']) {
            return 0;
        }
        return ($a['title']['rendered'] < $b['title']['rendered']) ? -1 : 1;
    }
    
    $ar = json_decode($yourJson, TRUE);
    usort($ar, "cmp");
    
    ...
    
    ?>
    
    Login or Signup to reply.
  2. use this function to sort any array

    function array_sort($array, $on, $order = SORT_ASC)
    {
        $new_array = array();
        $sortable_array = array();
    
        if (count($array) > 0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }
            switch ($order) {
                case SORT_ASC:
                    asort($sortable_array);
                    break;
                case SORT_DESC:
                    arsort($sortable_array);
                    break;
            }
    
    
            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $array[$k];
            }
        }
    
        return $new_array;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search