Search code examples
phpwordpressif-statementcustom-post-type

WordPress if post.php but only for one Custom Post Type


This is for the back end. The admin area. I have a script to run some functions but only for the Events custom post type created by the Events Calendar. Currently I have this script running in my functions.php:

if ($page == "post-new.php" OR $page == "post.php" ) {
    do something.....;
}

So it works, but on anything with post-new.php or post.php. Not good since this involves fields only related to the Events CPT. How can I get it to work exclusively on this CPT?


Solution

  • Typically, you can rely on the get_current_screen() function to return the data of what admin page you're on:

    $current_screen = get_current_screen();
    
    if( $current_screen->base == 'post' && $current_screen->post_type == 'your-post-type-here' ){
        // Do things
    }
    

    There's also the $post_type Global Variable but honestly, I don't see it used too much.