phpwordpresswordpress-gutenberg

Enqueing a script in functions.php using is_page not working


Can anyone help me enqueue a script condtionally on certain pages using the backend block editor?

Nothing I try is working using is_page() from the developer documentation, and I can't understand why, function calls without the if statement.

function alerts_enqueue() {
    if (is_page( 'Page Title' ) ) {
        wp_enqueue_script('alerts-script', get_stylesheet_directory_uri() . '/js/alerts.js', true);
    }
}
add_action( 'enqueue_block_editor_assets', 'alerts_enqueue' );

Solution

  • The issue you're facing is due to is_page() is only available on the frontend and is not availabe on the backend. There's a workaround to handle this specific scenario or your specific page. There are two options to do this.

    1. use get_current_screen() to check if you're on a specific post or page within the block editor:
    function alerts_enqueue() {
       $current_screen = get_current_screen();
       if('post' === $current_screen->base && get_the_ID() === xxx ) {
          wp_enqueue_script('alerts-script',get_stylesheet_directory_uri().'/js/alerts.js',array(),null,true);
       }
    }
    add_action('enqueue_block_editor_assets','alerts_enqueue');
    
    1. If you want to target by page slug:
    function alerts_enqueue() {
        $current_screen = get_current_screen(); 
        if('post' === $current_screen->base && get_post_field('post_name',get_the_ID()) === 'foo-bar-slug') {
           wp_enqueue_script('alert-script',get_stylesheet_directory_uri().'/js/alerts.js',array(),null,true); 
       }
    }
    add_action('enqueue_block_editor_assets','alerts_enqueue');
    

    for adding multiple slugs in the function you can do something like this:

    function alerts_enqueue() {
        $current_screen = get_current_screen();
        $target_slugs = ['foo-bar-slug', 'another-slug', 'yet-another-slug']; // Array of slugs you want to target
    
        if ('post' === $current_screen->base && in_array(get_post_field('post_name', get_the_ID()), $target_slugs)) {
            wp_enqueue_script('alert-script', get_stylesheet_directory_uri() . '/js/alerts.js', array(), null, true);
        }
    }
    add_action('enqueue_block_editor_assets', 'alerts_enqueue');
    

    *** Please Note *** You don't necessarily need to check 'post' === $current_screen->base if your only concern is determining the current post or page being edited in the block editor. However, the reason to include that check is to ensure you're in the block editor and not in another admin screen like the post list, media library, or settings.