Add Back Buttons to Edit Screens in the WordPress Admin

Add back buttons to edit screens in the wordpress admin image

Okay, okay. Seriously now… This is almost always the first snippet I install because when it’s not active I start twitching and can hardly function without it. Also, it’s sooooo handy when you’re editing your site on a mobile device, so you don’t have to dig through menus. Lazy===Good.

Before… eugghh 🤢

➡️

After… ahhh 🥹

What it does…

Attempts to add a “🔙” Back button to WordPress admin screens.

Why it does it…

Hopefully, it saves you time from needing to scroll and find the admin menu links.

How it does it…

Adds a javascript to the admin footer that tries to determine the parent admin page of the page you’re currently on. I’ve re-written this a couple times and the current version is my best yet, but if it’s missing something for you, lemme know!

See the code…

<?php

if (!class_exists('AdminBackButton')) {
	// Add Back Buttons to Edit Screens in the WordPress Admin [SnipSnip.pro] - https://snipsnip.pro/s/39
	// https://codesnippets.cloud/snippet/brandonjp/AdminBackButton
    class AdminBackButton
    {
        public function __construct()
        {
            if (is_admin() && current_user_can('manage_options')) {
                add_action('admin_footer', array($this, 'add_script_to_page'));
            }
        }

        public function add_script_to_page()
        {
            global $pagenow;

            $pages = array(
                'admin.php',
                'edit-tags.php',
                'user-new.php',
                'user-edit.php',
                'profile.php',
                'plugin-install.php',
                'media-new.php',
                'comment.php',
                'post.php',
                'term.php',
                'post-new.php',
            );

            if (in_array($pagenow, $pages)) {
?>

<script type="text/javascript">    
(function ($) {

/**
 * Add Back Buttons to Edit Screens in the WordPress Admin - AdminBackButton [SnipSnip.pro] - https://snipsnip.pro/s/39
 * The button attempts to correclty link to the parent, list or previous screen as applicable.
 * Author: brandonjp.com
 * Version: 2023-10-19
 */

  class AdminBackButton {
    constructor(config) {
      this.config = {
        backButtonClass: 'page-title-action customBackBtn',
        backButtonIcon: '‹',
        delay: 1500,
        styles: '',
        ...config,
      };
    }

    init() {
      $(document).ready(() => {
        if (window.jQuery) {
          this.addTheBackButtonDelayed();
        }
      });
    }

    addTheBackButtonDelayed() {
      setTimeout(() => {
        this.addTheBackButton();
      }, this.config.delay);
    }

    addTheBackButton() {
      const phpFile = this.getFileName();
      const $currentParent = $('#adminmenu > li').filter('.current, .wp-has-current-submenu');
      const $currentItem = $currentParent.find('ul.wp-submenu li.current').first() || $currentParent;
      const $firstItem = $currentParent.find('ul.wp-submenu li.wp-first-item').first() || $currentParent;
      const $newTarget = this.getTarget($currentItem, $firstItem, phpFile);

      if ($newTarget && $newTarget.length) {
        this.addBackButtonToHeader($newTarget);
      }
    }

    getFileName() {
      const pathArray = window.location.pathname.split('/');
      return pathArray[pathArray.length - 1];
    }

    getTarget($currentItem, $firstItem, phpFile) {
      if (this.config.filesWithConditionalDirection.includes(phpFile)) {
        const currentScreenSearch = window.location.search;
        const currentItemSearch = $currentItem.find('a').attr('href').split('php')[1];
        if (currentScreenSearch && currentItemSearch && currentScreenSearch === currentItemSearch) {
          this.config.filesGoingToCurrent.push(phpFile);
        } else {
          this.config.filesGoingToFirst.push(phpFile);
        }
      }
      return this.config.filesGoingToCurrent.includes(phpFile) ? $currentItem : this.config.filesGoingToFirst.includes(phpFile) ? $firstItem : undefined;
    }

    addBackButtonToHeader($newTarget) {
      const newHref = $newTarget.find('a').attr('href');
      const currentScreenHref = window.location.href.split('/').pop();
      const newHrefIsUnique = newHref && newHref.length && newHref !== currentScreenHref;

      if (newHrefIsUnique) {
        const newTitle = $newTarget.text().trim();
        const $heading = $('div.wrap > h1').first();
        const $newBtn = $('<a>', {
          href: newHref,
          title: newTitle,
          class: this.config.backButtonClass,
          text: this.config.backButtonIcon,
        });
        $heading.prepend($newBtn);
        console.log('Snippet: Add Back Buttons to Edit Screens in the WordPress Admin - AdminBackButton [SnipSnip.pro] - https://snipsnip.pro/s/39');
      }

      if (this.config.styles) {
        const $styleTag = $('<style>', {
          html: `.${this.config.backButtonClass.split(' ').join('.')} { ${this.config.styles} }`,
        });
        $('head').append($styleTag);
      }
    }
  }

  const adminBackButton = new AdminBackButton({
    filesGoingToFirst: [
      'admin.php',
      'edit-tags.php',
      'user-new.php',
      'user-edit.php',
      'profile.php',
      'plugin-install.php',
      'media-new.php',
      'comment.php',
    ],
    filesGoingToCurrent: [
      'post.php',
      'term.php',
    ],
    filesWithConditionalDirection: ['post-new.php'],
    backButtonClass: 'page-title-action customBackBtn',
    backButtonIcon: '‹',
    delay: 1500,
    styles: 'margin: 0 4px; border-radius: 3px;',
  });

  adminBackButton.init();
})(jQuery);
    
</script>

<?php
            }
        }
    }

    $adminBackButton = new AdminBackButton();
}