How to use foreach loop to echo in my code

Viewed 17

This may be basic but, I found this code

function get_sorted_categories( $order_by = 'id' ){
    global $wpdb;

    $category = get_categories();

    $order = [
        'id' => 'post.ID',
        'date' => 'post.post_date',
        'modified' => 'post.post_modified',
    ];

    $order_by = $order[ $order_by ];

    $q = $wpdb->get_results("SELECT tax.term_id FROM `{$wpdb->prefix}term_taxonomy` tax
    INNER JOIN `{$wpdb->prefix}term_relationships` rel ON rel.term_taxonomy_id = tax.term_id
    INNER JOIN `{$wpdb->prefix}posts` post ON rel.object_id = post.ID WHERE tax.taxonomy = 'category' AND post.post_type = 'post' AND post.post_status = 'publish' ORDER BY {$order_by} DESC");

    $sort = array_flip( array_unique( wp_list_pluck( $q, 'term_id' ) ) );

    usort( $category, function( $a, $b ) use ( $sort, $category ) {
        if( isset( $sort[ $a->term_id ], $sort[ $b->term_id ] ) && $sort[ $a->term_id ] != $sort[ $b->term_id ] )
            $res = ($sort[ $a->term_id ] > $sort[ $b->term_id ]) ? 1 : -1;
        else if( !isset( $sort[ $a->term_id ] ) && isset( $sort[ $b->term_id ] ) )
            $res = 1;
        else if( isset( $sort[ $a->term_id ] ) && !isset( $sort[ $b->term_id ] ) )
            $res = -1;
        else
            $res = 0;

        return $res;
    } );

    return $category;
}

print_r( get_sorted_categories('date') );


I want the result to appear as list intead of print_r.

I have been trying this

$list = get_sorted_categories('date');

foreach ($list as $items){ echo $items; }

but it doesn't work

1 Answers

get_sorted_categories will return an array of term objects, that you can loop and in your loop you'll single an object, using that object you can access object properties term_id, name, slug, etc.

I am not in which format you want to display them but you can check the below links to see some examples, and then you can try your code according to your need.

https://developer.wordpress.org/reference/functions/get_categories/#user-contributed-notes

Related