snippet for most views per cpt

  • Posted 3 weeks ago

We read that the amount of views is not stored.

ChatGPT suggested this code below. Will this work?

Step 1 – Store views in post meta

Add this to your child theme’s functions.php or via the Code Snippets plugin:

// Count views on single posts (also works for Voxel CPTs)
function vx_count_post_views() {
if ( is_singular() ) {
global $post;

$post_id = $post->ID;
$meta_key = ‘vx_post_views’;

$views = (int) get_post_meta( $post_id, $meta_key, true );
$views++;
update_post_meta( $post_id, $meta_key, $views );
}
}
add_action( ‘wp’, ‘vx_count_post_views’ );

What this does:

Every time a single post/page is loaded → vx_post_views is increased by 1.

Works for posts and Voxel custom post types, as long as they use a singular template (is_singular()).

If you want to limit it to a specific CPT, you can add:

if ( get_post_type( $post_id ) !== ‘your_cpt_slug’ ) return;

Step 2 – Use the meta key in Voxel as “order by” / filter

In the Voxel editor:

Open your Post Feed (VX) template.

Go to the Query settings.

Add a new Order by rule:

Type: Meta key

Meta key: vx_post_views

Type: NUMERIC

Order: DESC