How can I use is_page () inside the plugin?

I want my plugin to register the script only on a specific 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 is being called incorrectly. Conditional request tags do not work before executing the request. Before that, they always return false. please see the "Debugging in WordPress" section for more information. (This post was added in version 3.1.)

How can I register a script on a specific page inside a plugin?

+4
source share
3 answers

is_page() only works in template files.

, template_redirect action hook.

, WordPress , .

, :

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 );
    }
}
+10

is_page() , :

add_action('template_redirect','your_function');
function your_function(){
 if ( is_page('test') ) {
  // do you thing.
 }
}
+2

script, , . , :

function deregister_my_script() {
    if (!is_page('page-d-exemple') ) {
        wp_deregister_script( 'custom-script-1' );
    }
}
add_action('wp_print_scripts', 'deregister_my_script', 100 );
0
source

Source: https://habr.com/ru/post/1529214/


All Articles