The First Problem
The cause of this is not a WP problem, but a fundamental misunderstanding of how HTML forms work.
To be specific, the problem is here:
if( isset($_POST['clicks']) ) {
There is no input named clicks
, so this value is never set ( because you never set it ).
Lets look at your form:
<form action="<?php echo get_bloginfo('home')?>" method="post">
<input type="submit" value="click me!" name="clicks">
</form>
<p>Click Count: <?php echo get_user_meta('click_count', $current_user, true); ?></p>
<?php } ?>
Here, it submits a form to the homepage using POST
, but it never sends any information. The only input
tag is the submission button. A hidden input is needed with the name
of clicks
The Second Problem
$current_user = wp_get_current_user();
if( isset($_POST['clicks']) ) {
setcount($userID);
Here, the code fetches the current user, but then passes $userID
to setcount
. $userID
is not defined anywhere though, it has no value, so PHP defaults it to null
or an empty value. This is why even if you submit the form succesfully, it fails to update the database
A Final Note
If you double click the submit button, the code will enter a race condition as multiple requests try to increment the value. Depending on how fast the server is, the server load, and how quickly the user double clicks, the count will increment, or it will increment by 2 instead of 1.
So disable the submit button after it’s clicked via javascript