Solving the Problem of WordPress View Counts Not Increasing After Enabling a CDN

4,301 0

After enabling CDN static page caching in WordPress, when an article is accessed, the origin server is not requested; instead, the page cached by the CDN is returned. As a result, the article view count will not automatically increase or undergo any other changes.

To solve this problem, you can use Ajax to send an asynchronous request to the server, and then increase the article view count or perform other operations.

Important reminder:

This method is only applicable to blogs using the WP-PostViews plugin or the same field as WP-PostViews. If your article statistics field is different, you can modify the SQL statement below as needed to achieve the desired result.

Solution

First, create a PHP file in the root directory of WordPress, name it views.php, and then write the following code into the file:

PHP
<?php require('wp-blog-header.php'); ?>
<?php
  $ajaxHead =  $_SERVER['HTTP_X_REQUESTED_WITH'];
  if (strtoupper($ajaxHead) == strtoupper("XMLHttpRequest")) {
    $post_id = $_POST['post_id'];
    echo $post_id;
    $sql = "update wp_postmeta set meta_value = meta_value + 1 where post_id = '${post_id}' AND meta_key = 'views';";
    $wpdb->query($sql);
  } else {
    header("HTTP/2 404 Not Found");
    header("Status: 404 Not Found");
    exit;
  }
?>

In the code above, an Ajax request header validation is performed to prevent malicious requests and verify whether the request is an XMLHttpRequest. If it is not, a 404 status is returned.

Next, insert the following JS code into the theme's page.php file:

HTML
<script>
  $(function() {
    $.post("/views.php", { post_id: <?php the_ID(); ?> }, function() {});
  });
</script>

This completely solves the problem of WordPress article views failing to increase after CDN caching is enabled.

Comments

(0)

No comments yet. Start the conversation.

Leave a comment