I know it is possible to filter queries to order posts by the numeric value of a meta. For example, I store the number of total likes for a post in a single meta key :

            $query->set('meta_key', 'total_likes' );
            $query->set('order', 'DESC');

But I would like to filter my query to order posts by the recently viewed items.
To achieve this, I store the time the item was liked in another meta key, which is not single. Each time a 'time_liked' meta is added, I check the other ones to remove those which are too old.

Does something like this exists; or how can I achieve it ?

            $query->set('meta_key', 'time_liked' );
            $query->set('orderby', ...); //something like meta_count ?
            $query->set('order', 'DESC');

1 Answer 1


Finally found out using two (single) posts metas :

  • likes_log where I keep up to date an array where each entry is the time the item was liked. Entries are removed if they are too old (here, >1 month)
  • likes_log_count where I update the number of entries in the previous log.

    function update_likes_monthly_count(){
        if ( get_post_status($this->post_id) != 'publish') return;
        $log = array();
        $time = current_time( 'timestamp' );
        $time_remove = strtotime('-1 month',$time); 
        if ($existing_log = get_post_meta($this->post_id, 'likes_log', true)){ //get month log
            $log = $existing_log;
        //remove entries that are too old from log metas (multiple)
        foreach ((array)$log as $key=>$log_time){
            if ($log_time <= $time_remove){
        //update log
        $log[] = $time;
        update_post_meta($this->post_id, 'likes_log', $log);
        //update likes count
        $count = count($log);
        return update_post_meta($this->post_id, 'likes_log_count', $count );

then, I can use 'likes_log_count to filter my query !

        $query->set('meta_key', 'likes_log_count' );
        $query->set('order', 'DESC');

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.