0

I am trying to create a simple checkbox setting that toggles a section in a blog post on or off in a theme settings page.

Unfortunately it's not saving the checkbox setting. I check the box and when I refresh the page it is unchecked again. Either it is not saving the setting or the checked function isn't working. Am I missing something?

function theme_option_settings(){
    register_setting( 'prev-next-setting', 'prev-next' );
    add_settings_section( 'blog-section', 'Blog Section', 'change_blog_layout_section', 'theme-options' );
    add_settings_field( 'show-prev-next', 'Show Previous/Next Post Section', 'show_prev_next_field', 'theme-options', 'blog-section' );
}

function change_blog_layout_section(){
    echo "Change the blog layout section";
}

function show_prev_next_field(){
    echo get_option( 'prev-next' );
    echo "<input type='checkbox' id='prev-next' name='prev-next' value='1' ".checked(1, get_option('prev-next'), true)."/>";
}
  • The last argument of checked(), $echo, should be false, because you're already using it as part of an echo statement. If you just need to include it in a string, you need to return it. – Jacob Peattie Oct 9 '18 at 12:40
  • I just changed that but it still won't save the checked setting. – danny471 Oct 9 '18 at 12:58
  • Also, the value of the checkbox is '1', a String, but you're using 1, an integer, in the checked() function. The types need to match. Use '1' (in quotes) in the checked function. – Jacob Peattie Oct 9 '18 at 13:00
  • Just try replacing - in 'prev-next' with underscore. We should not use - in name or id of any html control – Aparna_29 Oct 9 '18 at 14:22
0

I managed to figure this out. It was because on the template page where I output the form I had forgotten to include the settings_fields function, so it was not saving the setting. I added the following code below to that page and then it worked:

<?php settings_fields('prev-next-setting'); ?>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.