2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

set_current_screen() 前に管理画面のポストタイプだったりを取得するクラス

Last updated at Posted at 2017-08-16

after_setup_theme だったり init など、$GLOBALS['typenow']$GLOBALS['taxnow'] が定義されていない段階で取得する。
###code

<?php

class WPQuickScreen {

	/**
	 * @var string
	 */
	private $pagenow;

	/**
	 * @var null|string
	 */
	private $typenow;

	/**
	 * @var null|string
	 */
	private $taxnow;

	private static $query_filter_diffinitions = array(
		'action'    => \FILTER_SANITIZE_ENCODED,
		'post_type' => \FILTER_SANITIZE_ENCODED,
		'taxonomy'  => \FILTER_SANITIZE_ENCODED,
		'post'      => \FILTER_VALIDATE_INT,
		// and more
	);

	public static function getInstance() {
		static $instance;
		return $instance ?: $instance = new self();
	}

	public function __get( $name ) {
		return property_exists( $this, $name ) ? $this->$name : null;
	}

	private function __construct() {
		if ( ! is_admin() ) {
			return;
		}
		global $pagenow;
		$this->pagenow = $pagenow;
		$this->parse_query();
	}

	private function parse_query() {
		$q = filter_input_array( INPUT_GET, self::$query_filter_diffinitions );
		switch ( $this->pagenow ) {
			case 'edit.php' :
			case 'post-new.php' :
				$this->typenow = $q['post_type'] ?: 'post';
				break;
			case 'post.php' :
				/**
				 * @see https://ja.forums.wordpress.org/topic/150122
				 */
				$this->typenow = $q['post'] ? get_post_type( $q['post'] ) : filter_input( \INPUT_POST, 'post_type' );
				break;
			case 'edit-tags.php' :
			case 'term.php' :
				$this->taxnow = $q['taxonomy'] ?: 'post_tag';
				break;
			case 'index.php' :
				// var_dump( 'Dashboard!!!!!' );
				break;
		}
	}

}

###usage

function.php
<?php
add_action( 'after_setup_theme', function() {
	if ( !is_admin() ) {
		return;
	}
	global $pagenow;
	var_dump( $typenow ); // null

	$qscreen = WPQuickScreen::getInstance();
	var_dump( $qscreen->typenow );
} );
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?