• Hi,
    I’ve implemented a simple sorting dropdown and would like to add “Most Likes” to that list. At the moment I am reloading the archive page and adding a “?orderby=’date’&order=’dsc'” to the URL. Is there a way to get the wp-ulikes in a similar way?

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter pend00

    (@pend00)

    I’ll answer my own question if someone needs help with this in the future.

    You can simply add ?orderby=’date’&order=’dsc' at the end of an archive URL and WordPress will recognize it and order the archive accordingly. However, this doesn’t work with properties that aren’t predefined by WordPress, so doing something like ?orderby=’likes’&order=’dsc' will do nothing.

    But you can check for the value of orderby in a PHP function before the archive is generated and if it is ‘likes’ then modify the query. ULike has a function to get posts sorted by likes, wp_ulike_get_popular_items_ids(). So my code at the end looked like this (it’s a bit simplified for demonstration):

    HTML:

    <select name="sort" id="sort" onchange="document.location.href=\'?\' + this.options[this.selectedIndex].value" class="archive_sort_dropdown">
    [...]
        <option value="orderby=likes" class="archive_sort_dropdown_item" >Most liked</option>
    [...]
    </select>

    PHP:

    add_action('pre_get_posts', 'most_liked_query');
    
    function most_liked_query($query)
    {	
    	
        if($_GET['orderby'] == 'likes'){
            $post__in = wp_ulike_get_popular_items_ids(array(
                "rel_type"   => 'article', //post type
                "period"     => 'all', //all time, I think you can set week, day etc
                "limit"      => 0 //how many posts to get, I think 0 is all posts
            ));	
    
            $query-> set('post__in', $post__in);
            $query-> set('orderby', 'post__in');
            
            return $query;
        }
    }
    • This reply was modified 3 years, 1 month ago by pend00.

    Hey @pend00

    Your solution works perfectly! But I had to do a little tweak, your form “onchange” didn’t work out for me, so and I was getting a wrong url ?sort=orderby%3Dlikes

    So I’ve modified it in this way:

    <form>
    
    <select name="orderby" id="orderby" onchange="document.location.href=\'?\' + this.options[this.selectedIndex].value" class="archive_sort_dropdown">
    [...]
        <option value="likes" class="archive_sort_dropdown_item" >Most liked</option>
        
    [...]
    </select>
    
    <input type="submit">
    
    </form>

    Can you check why yours didn’t work?

    Cheers!

    • This reply was modified 3 years, 1 month ago by djekanovic.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sort by likes with “orderby”’ is closed to new replies.