Last active
August 29, 2015 14:09
-
-
Save ibrokemywp/62f3e31b53c98c599ea7 to your computer and use it in GitHub Desktop.
get_current_screen() returns null in ajax requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Let's say you're parsing query args in the admin so | |
* that you can apply some custom filters for your | |
* custom post type list table. | |
*/ | |
add_filter( 'parse_query', 'filter_my_post_type' ); | |
function filter_my_post_type( $query ) { | |
/** | |
* Oh good, you've put in that is_admin() check | |
* so it won't effect the front-end. | |
*/ | |
if ( !is_admin() || empty( $query->query['post_type'] ) || $query->query['post_type'] !== 'my_post_type' ) { | |
return; | |
} | |
/** | |
* So we know we're in the admin now, right? | |
* Let's get that screen to make sure we're | |
* only effecting queries on our post type's | |
* list table page. | |
*/ | |
$screen = get_current_screen(); | |
if ( $screen->post_type == 'my_post_type' ) { | |
/** | |
* Woops, someone just queried your | |
* custom post type in an ajax call | |
* from the Customimzer. The | |
* ajax call passes the is_admin() | |
* check but no screen exists. WP_DEBUG | |
* was enabled so you just caused a | |
* PHP Notice that breaks the JSON | |
* response to the ajax call. | |
* | |
* Check you have a screen object | |
* before relying on it! | |
* | |
* is_object( $screen ) | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment