Post Views using Post Meta in WordPress

Overview

View counts help highlight popular content. Storing counts in post meta (_post_views) avoids a separate analytics table for basic use cases.

Increment on wp hook for singular posts, excluding admin, feeds, and bots when possible.

Implementation

Register meta if using the REST API. On single post load, read current count, increment, and update_post_meta. Display with get_post_meta in templates or a shortcode.

Debounce bots by checking is_preview(), logged-in editors, or using a transient per IP for high traffic.

When implementing guidance from Post Views using Post Meta in WordPress, start in a controlled environment that mirrors production versions of operating systems, runtimes, and network policies. Capture a baseline before changes: export configs, snapshot VMs, or tag releases in source control so rollback stays straightforward if behavior regresses.

Document prerequisites, expected outcomes, and verification steps in a short runbook. Automated checks—smoke tests, health endpoints, or query validations—catch regressions early when platforms receive patches. Security belongs in every workflow: apply least privilege, rotate secrets, and review audit logs after deployment.

If results differ across machines, compare environment variables, permission models, time zones, and regional settings. Intermittent issues often trace to caching layers, stale DNS, or duplicated services bound to the same port.

Example

add_action('wp', function() {
  if (!is_singular('post') || is_user_logged_in()) return;
  $id = get_queried_object_id();
  $n = (int) get_post_meta($id, '_post_views', true);
  update_post_meta($id, '_post_views', $n + 1);
});

Tips

  • High-traffic sites should use Redis or an analytics service.
  • Do not count admin previews.
  • Object cache plugins may batch meta writes.
  • GDPR: inform users if tracking individuals.
  • Re-verify after reboots, certificate renewals, or failover exercises.
  • Align monitoring and alerts with the failure modes described in this guide.
  • Keep vendor documentation links handy for breaking changes between versions.
  • Pair automation with a manual spot check during initial production rollout.