0

I am trying to set up a redirect that is toggleable via admin backend, using a checkbox. Here is my redirect function:

function redirect_to_prelaunch_page()
{
  if (get_current_user_id() == 0 && !is_page("pre-launch.html"))
{
   wp_redirect( 'https://prettygals.co.uk/pre-launch.html', 301 );
   exit;
}
}

This redirect works great in my theme's functions.php, but i'd like to include it in my plugin.

Below is the code i've got for my plugin:

<?php

//redirect to pre-launch page if not logged in and not on pre-launch page already

function redirect_to_prelaunch_page()
{
  if (get_current_user_id() == 0 && !is_page("pre-launch.html"))
{
   wp_redirect( 'https://prettygals.co.uk/pre-launch.html', 301 );
   exit;
}
}


//create custom plugin settings menu
add_action('admin_menu', 'pg_base_plugin_create_menu');

function pg_base_plugin_create_menu() {

  //create new top level menu
  add_menu_page('PrettyGals Base','PrettyGals Base', 'administrator', __FILE__, 'pg_base_plugin_settings_page', '', 9999999 );

  //call register settings function
  add_action('admin_init', 'register_pg_base_plugin_settings');
}

function register_pg_base_plugin_settings() {
  //register settings
  register_setting('pg_base', 'pg-prelaunch');
}

function pg_base_plugin_settings_page() {
  ?>
  <div class="wrap">
    <h1>PrettyGals Base</h1>

    <form method="post" action="options.php">
      <?php settings_fields('pg_base'); ?>
      <?php do_settings_sections('pg_base'); ?>
      <table class="form-table">
        <tr valign="top">
          <th scope="row">Pre-Launch</th>
          <td><input type="checkbox" name="pg-prelaunch" value="1" /></td>
        </tr>
      </table>

      <?php submit_button(); ?>

    </form>
  </div>
<?php } ?>

It all works as it should (as in the checkbox etc shows up as it should), but i'm not sure where to go from here.

I figured i'd use IF checkbox == checked then call the function the redirect is in. Is this right?

Also, the checkbox doesn't stay checked when submitting, any idea why or how to fix this?

I am still learning so any help is greatly appreciated. I was referencing this page to create this.

Cheers, D

  • "the checkbox doesn't stay checked when submitting" - from the examples you've linked, it looks like you need to read the current value yourself and write your own checked="checked" attribute into the <input> if it's set. – Rup Apr 12 at 16:03
  • You're missing half of the necessary functions from the Settings API. codex.wordpress.org/Settings_API – MikeNGarrett Apr 12 at 17:00

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.