Keeping any data that doesn’t need to be sent back to the server with every request in cookies is inefficient. WordPress by default will save the name, email address, and home page of any user that leaves a comment in three separate cookies. Each subsequent request to the server will then contain this mostly useless data that just slows things down and introduces hurdles for efficient intermediary caching.
In this article, I’ll walk you through how to either disable the storing of this data entirely, or move the data into
localStorage and just keep it locally on visitors’ devices.
There are two equivalent ways you can prevent the server from setting these cookies when a user leaves a comment. Either include the following line of code in your theme’s
Or install the Cookieless Comments plugin, which will take care of including the above one-line of code for you.
At this point, the data on the commenter is only preserved in your WordPress database and the commenter’s browser is no longer retaining this information for future visits. If this is what you wanted, then you’re done. If you do want to preserve the data in the visitor’s browser, however, keep on reading.
Saving data in
localStorage when they submit a comment, and retrieves it if there’s a comment form on the page on later visits.
You can include it on your post pages however you like; for example as part of another script or as a separate file. If you store it in a separate file, you can include it only on pages where comments are enabled (not strictly required, but nice for performance on uncommentable pages). The following example demonstrates how to use WordPress conditionals to only include a script on pages that accept comments:
If you want to get all cheesy with the visitor, you can now start greeting them by name by reading out the
'comment_author' key from
localStorage. A more useful application of this data is to highlight the visitor’s own comments or even replies to their own comments.
I intend to come back to why changing away from using cookies may be necessary in an upcoming article. Subscribe to the newsletter to make sure you catch it!