This is more complicated than it appears. One thing is you probably want to only count unique member views. If the same member re-loads the page it shouldn’t count as another view, or is that what you intent? If the first case, you would not only need to count visits, but keep track of which users visited.
You also may wish to not count certain users such as admins, editors, authors, etc. Additionally, those same users may need to be able to view the page even after 10 views.
On public pages, one also needs to consider that a significant portion of requests are not human users. Reliably determining whether a request for a public page is from a real human or not can be a challenge. Fortunately, you are only counting logged in members, so it’s safe to assume all members are human ??
What you do also depends on whether the code needs to be implemented as a plugin or if it can be part of a child theme. It makes more sense to have the tracking code as part of a custom page template. Thus only pages based on the template are restricted, other posts and pages can work as normal without restriction.
Custom page templates are much easier to implement on a child theme. Plugins are not intended to provide templates, doing so involves some special code to fool WP into thinking the plugin templates are part of the theme.
You can use post meta to store the data: the running count of views and an array of user IDs that have viewed. The entire page template is divided into two parts: one to show the content, and one to redirect when the count is exceeded. Some code before these parts decides which part to serve.
First check if the user is one of those who can always view the content (admin, etc.). Then check if the current user ID is in the saved array. Finally, check if the post count is less than 10. If any of those checks are true, display the content, otherwise redirect.
Part of the content section not only displays the current count, but increments the counter in post meta and adds the current user’s ID to the saved viewer array. But this is only done for a common, new user. If the user is admin, editor, or author; or the user ID was already in the array, the count is not incremented and the ID is not stored.
Note that you cannot use PHP’s header()
to redirect because page output had already begun. You need to send a <script>
block that does the redirect through JavaScript. The common content like header, footer, etc. will load before the redirect occurs, but for most people it’ll be very short, barely enough time to read some simple content like “Redirecting…”.