We’re going to use an ACF and a little bit of PHP.

Let’s add an ACF custom field to keep a count of views on any post, add this to your code:

if( function_exists('acf_add_local_field_group') ):

acf_add_local_field_group(array(
    'key' => 'group_name_here',
    'title' => 'My Group Name',
    'fields' => array (
        array (
            'key' => 'field_some_random_key_here',
            'label' => 'Page Views',
            'name' => 'page_views',
            'type' => 'number',
            'instructions' => 'Used for most-read posts.',
            'required' => 0,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '25',
                'class' => '',
                'id' => '',
            ),
            'default_value' => '',
            'placeholder' => '',
            'prepend' => '',
            'append' => '',
            'min' => '',
            'max' => '',
            'step' => 1,
            'readonly' => 1,
        )
    ),
    'location' => array (
        array (
            array (
                'param' => 'post_type',
                'operator' => '==',
                'value' => 'post',
            ),
        ),
    ),
));

endif;

Okay, now we need a PHP function to increment the post views field when we view it. This could go in your single.php file, or whatever page your theme uses to display posts. You could also declare it in any included function file, so long as it is accessible on your post page.

function do_count_post_views($post_id) {
    $num_views = get_field('page_views', $post_id);
    if (!is_numeric($num_views)) :
        $num_views = 1;
    endif;
    update_field( 'page_views', ++$num_views, $post_id);
}

Now in single.php or your custom post page to call the increment function add this:

<?php do_count_post_views($post->ID); ?>

Finally the code to display the list, put this wherever, you like, perhaps on your front-page.php or in a sidebar-front.php type page:

<?php
$args = array(
    'post_type' => array('post'),
    'post_status' => array('publish'),
    'posts_per_page' => 6,
    'meta_key' => 'page_views',
    'orderby' => array(
        'meta_value_num' => 'DESC'
    ),
    'tax_query' => '',
    'date_query' => array(
        array(
            'after' => '1 week ago'
        )
    )
);
$query = new WP_Query($args);
?>

<?php if ( $query->have_posts() ) : ?>

    <p>Most read</p>
    <ol>
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
        <li>
            <a href="<?= get_permalink($post->ID); ?>"><?= esc_attr( get_the_title( $post->ID ) ); ?></a>
        </li>
        <?php endwhile; ?>
    </ol>
<?php endif; ?> 

And that’s it!

Last modified: June 27, 2023

Author

Comments

Write a Reply or Comment

Your email address will not be published.