Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use is_page() inside a plugin?

Tags:

wordpress

I want my plugin to register a script only in a certain page.

For example, inside my plugin file I want to write something like this:

if (is_page()) {
    $pageid_current = get_the_ID();
    $page_slug = get_post($pageid_current)->post_name;

    if ($page_slug == 'articles'){
        wp_register_script('myscript', '/someurl/main.js');
    }
}

But I get the error:

is_page was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.)

How can I, inside of a plugin, register a script in a certain page?

like image 361
Weblurk Avatar asked Feb 27 '14 13:02

Weblurk


1 Answers

is_page() only work within template files.

And to use it within plugin files, you need to use it with the combination of template_redirect action hook.

This action hook executes just before WordPress determines which template page to load.

So following snippet would work:

add_action( 'template_redirect', 'plugin_is_page' );

function plugin_is_page() {
    if ( is_page( 'articles' ) ) {
        wp_register_script( 'my-js-handler', '/someurl/main.js', [], '1.0.0', true );
    }
}
like image 69
Rahil Wazir Avatar answered Sep 23 '22 12:09

Rahil Wazir