1

I have a function that records the post views, and my post loops can be ordered by post views. This is the code:

/**
 * Set Post views
 *
 */
function hp_global_set_post_views() {
    if (!is_single()) 
        return;

    global $post;
    $post_id = $post->ID;    

    $view_count = get_post_meta($post_id, 'view_count', true);
    $view_count++;
    update_post_meta($post_id, 'view_count', $view_count);
}
add_action('wp_head', 'hp_global_set_post_views');

/** example query args to order posts by veiw count */
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query_args = array(
    'paged'    => $paged,
    'orderby'  => 'meta_value_num',
    'order'    => 'DESC',
    'meta_key' => 'view_count'
);

If you have a website with large traffic, would it be better to create a new column in the _posts table called 'view_count' and then update that column everytime a post gets a view instead of creating a new row for each post in the post meta?

And the QP_QUERY args can be written like:

// args to Order posts by veiw count
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query_args = array(
    'paged'    => $paged,
    'orderby'  => 'view_count',
    'order'    => 'DESC'
);

I'm really unsure of the best way to structure a database for a website for the best performance. Why would this be a good idea or bad idea. Any help appreciated.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.