is_page() function doesnt working

I’m trying to add these custom CSS and JS (written inside a custom plugin) only add to a specific page.

this is my code

<?php   

function randomAlphaNumeric($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
    $key='';
    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}



add_action('init', 'register_script');
function register_script(){
    if(is_page('page_title')) {
        wp_register_script( 'custom_js', plugins_url('/js/custom-js.js', __FILE__).'?random='.randomAlphaNumeric(5), array('jquery'));
        wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__).'?random='.randomAlphaNumeric(5), false, 'all');
    }
}


// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
    if(is_page('page_title')) {
        wp_enqueue_script('custom_js');
        wp_enqueue_style( 'new_style' );
    } 
}

but is_page() doesn’t seem to work at all..
I tried to change it with ID and SLUG, but no success

UPDATE
replaced condition to check the page title, still doesnt work

add_action('init', 'register_script');
function register_script(){
    global $post;
    if($post->post_title == 'page_title') {
        wp_register_script( 'custom_js', plugins_url('/js/custom-js.js', __FILE__).'?random='.randomAlphaNumeric(5), array('jquery'));
        wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__).'?random='.randomAlphaNumeric(5), false, 'all');
    }
}


// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
    global $post;
    if($post->post_title == 'page_title') {
        wp_enqueue_script('custom_js');
        wp_enqueue_style( 'new_style' );
    } 
}

2 Answers
2

The init hook is too early — WordPress hasn’t yet identified the queried object (post, category, etc.); hence the is_page() doesn’t work there:

add_action('init', 'register_script');

So for conditional tags/functions like is_page(), is_single(), etc. to work (i.e. return the proper result), you should use wp or a later hook:

add_action('wp', 'whatever_function');

But for registering/enqueueing scripts and styles, you should always use the wp_enqueue_scripts hook; so you would use this (and not the above):

add_action('wp_enqueue_scripts', 'register_script');

PS: Credits to @huraji for his helpful comment.

Leave a Comment