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)."/>";
}
4
  • 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. Commented Oct 9, 2018 at 12:40
  • I just changed that but it still won't save the checked setting. Commented Oct 9, 2018 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. Commented Oct 9, 2018 at 13:00
  • Just try replacing - in 'prev-next' with underscore. We should not use - in name or id of any html control Commented Oct 9, 2018 at 14:22

1 Answer 1

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 and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.