I am trying to make a small form, that just has a submit button, and on submission, it should toggle user meta for the WordPress user. The button exists on frontend after content of post, and has a action too.

<form action="https://milyin.com?dark=true" method="POST">
<input type="submit" name="test" id="test" onclick="https://milyin.com?dark=true"/><br/> </form>

The above was the html form code, i can assure that it echoes properly. Then i add the below line to trigger it. This is php

if (isset($_GET['dark'])){ 

This calls a function called testfun, the function testfun is below:

function testfun(){
$user_id = get_current_user_id();
$theme= get_user_meta($user_id, 'theme', true);
if ($theme == 'dark') {
   update_user_meta($user_id, 'theme', 'light');
   update_user_meta($user_id, 'theme', 'dark');

And obviously this code doesn't work, and i fail to figure our why. I have an intuition that the way i gey user id, can be wrong, because rest all seems to be fine. Anyhow please help me with this code.

I basically want to create a button that for the current logged in user, updated the user meta key 'theme' and toggles it between values 'light' and 'dark'

And as far as I am concerned i couldn't find anything wrong in it.

  • You should call the testfun() before you display the form - preferably in an early hook like template_redirect. Btw, your submit button contains an invalid onclick value. – Sally CJ Oct 6 '19 at 1:10
  • Well l shall test the function and let you know... But whats wrong with my button, the form syntax seems correct... Please explain.. – Aditya Agarwal Oct 6 '19 at 4:09
  • Hey I tested the function, i called it in some other function, and it works perfectly, the problem probably exists in the html or the if statement that calls the function.. – Aditya Agarwal Oct 6 '19 at 4:37
  • The onclick attribute should contain a valid JS expression/code, but yours (which is an URL) is not a valid one. And that doesn't answer the question, but you should correct it anyway. – Sally CJ Oct 6 '19 at 11:26
  • And can you re-clarify the question - is it when you submit the form, the function testfun doesn't run at all or that the meta value is not updated? Are you calling the function from within any hook or you just put it exactly below/after the form - <form>...</form><?php // here you call the function? ?>? – Sally CJ Oct 6 '19 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.