To track the number of views for each post in WordPress, you can create a custom function and use a combination of WordPress hooks and database operations. Here's an example of how you can achieve this:

Step 1: Create a custom table to store the post views count. You can use the following SQL query to create the table:

CREATE TABLE wp_post_views (
    id INT(11) NOT NULL AUTO_INCREMENT,
    post_id INT(11) NOT NULL,
    views INT(11) DEFAULT 0,
    PRIMARY KEY (id),
    UNIQUE KEY post_id (post_id)
);

Step 2: Add the following code to your theme's functions.php file to define the custom function:

function increment_post_views($post_id) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'post_views';
    
    // Check if the post ID exists in the table
    $views = $wpdb->get_var($wpdb->prepare("SELECT views FROM $table_name WHERE post_id = %d", $post_id));
    
    if ($views) {
        // If the post ID exists, increment the views count
        $wpdb->query($wpdb->prepare("UPDATE $table_name SET views = views + 1 WHERE post_id = %d", $post_id));
    } else {
        // If the post ID doesn't exist, insert a new row with views count as 1
        $wpdb->query($wpdb->prepare("INSERT INTO $table_name (post_id, views) VALUES (%d, 1)", $post_id));
    }
}

function track_post_views() {
    if (is_single()) {
        global $post;
        if ($post) {
            increment_post_views($post->ID);
        }
    }
}
add_action('wp_head', 'track_post_views');

Step 3: To display the post views count on the post, you can use the following code within your theme file (e.g., single.php):

<?php
global $post;
$views = $wpdb->get_var($wpdb->prepare("SELECT views FROM $wpdb->prefix" . "post_views WHERE post_id = %d", $post->ID));
echo 'Views: ' . $views;
?>

Make sure to modify the table name (wp_post_views) and prefix (wp_) in the code according to your WordPress installation.

With these modifications, the increment_post_views function will be called on each view of a single post, incrementing the views count in the database. The track_post_views function is hooked to the wp_head action, ensuring it's executed on each page load. Finally, the code snippet within the single.php file will display the post views count

i want function for post visit on each viewand also show count views in post by idin wordpress

原文地址: http://www.cveoy.top/t/topic/iVOO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录