0

I would like to show my most viewed categories (kind like the "WP-PostViews" plugin).

I already did some research but I didn't find nothing about that. This made me think that it can't be done by some reason and I would like to know more about it...

1

Wordpress doesn't record the visit statistics in the database. If you want to show top visited categories, you must then record statistics somewhere.

What's why there are plugins designed to fill out this need.

Of course, you can write your own code to record visits in the database. This will be a good starting point.

1

As Lucien already wrote, WordPress doesn't record any statistics by default. But...

You can easily do it by yourself. If you want only the total views count, then you can even use term meta to store that number. Here's the code that will count the views:

function my_count_views() {
    if ( is_category() ) {
        $views = intval( get_term_meta( get_queried_object_id(), 'category_views', true ) );
        update_term_meta( get_queried_object_id(), 'category_views', $views + 1 );
    }
}
add_action( 'template_redirect', 'my_count_views' );

So this uses template_redirect hook and if WP is about to display category archive, then it will get category_views meta field from current category, increment it by 1 and save it back as a meta.

There is only one problem - this way of counting views is very simple. You will get many bad views (bots, and so on) and if you'll use any caching on your site, the results won't be real.

So can you do it? Yes, you can. But should you?

IMHO no, you shouldn't. Storing statistical data in your own database is very inefficient and it will cause many problems, if your site gets many views.

So how I would do this? I would use Google Analytics and use its API to get the visits count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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