admin管理员组

文章数量:1332881

I'm working on a plugin that keeps track of like counts on every post in the site. When the plugin is activated a custom table is created to store all the data. The plugin then checks on every page load if a record exists in the table for that particular post id. The code looks like this:

function mpc_generate_html($content)
{
    global $wpdb;
    $obj = get_queried_object();
    $post_id = $obj->ID;


    $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE post_id = $post_id");

    if ($count == 0) {
        $wpdb->insert(sswc_table_name, array('post_id' => $post_id));
    }
    //More code here.
}

If the record does not exists for that post ID, it $wpdb->insert() that record into the table. Now the plugin is working fine on my local environment with like 3 posts. But in product its creating multiple records for the same postId which is not what i want. What am I doing wrong?

本文标签: Prevent duplicate records in plugin table