jordanmaslyn
1/8/2016 - 5:16 PM

Redirection CSV Plugin

Redirection CSV Plugin

<?php

// include this in your theme's functions.php file
// Find & Replace all instances of 'prefix' and replace with the brand name.
// the file itself expects to be in /wp-content/themes/prefix/functions/modules/

add_action( 'admin_menu', 'prefix_redirects_admin_menu' );

function prefix_redirects_admin_menu() {
  add_menu_page(
    'Site Redirects Administration',
    'Redirects Admin',
    'manage_options',
    'prefix-redirects-admin.php',
    'prefix_redirects_admin_page',
    'dashicons-randomize');
}

function prefix_redirects_admin_page() {
  $updated = false;

  if ($filedata = file_get_contents(dirname(__FILE__) . '/redirects.csv')) {
    $has_data = true;
    if (isset($_GET['updated']) && $_GET['updated'] == 'true') {
      $updated = true;
    }
  } else {
    $has_data = false;
    $error = "<h3>Sorry, no redirect data found! Please contact CO+LAB to resolve this issue.</h3>";
  }

  ?>
  <div class="wrap">
    <h2>Manage prefix Site Redirects</h2>
    <?php if ($updated): ?>
    <div class="notice is-dismissible updated">
      <p>Redirects were successfully updated!</p>
      <button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>
    </div>
    <?php endif; ?>
    <?php if ($has_data): ?>
      <div>
        <p>The correct format for this is to put the old path (with no trailing slash), followed by a comma, followed by the new path.</p>
      </div>
      <form action="/wp-admin/admin-post.php" method="post">
        <textarea name="redirect-data" id="redirect-data" style="width:100%; height: 300px;"><?= $filedata; ?></textarea>
        <input type="hidden" name="action" value="submit_prefix_redirects">
        <input type="submit" value="Submit" class="button button-primary">
      </form>
    <?php else: ?>
        <?= $error ?>
    <?php endif; ?>
  </div>
  <?php
}

add_action( 'admin_post_submit_prefix_redirects', 'submit_prefix_redirects' );

function submit_prefix_redirects() {
    file_put_contents(dirname(__FILE__) . '/redirects.csv', $_POST['redirect-data']);
    wp_redirect(admin_url('admin.php?page=prefix-redirects-admin.php&updated=true'));
    die();
}

?>