How can I use is_page() inside a plugin?

故事扮演 提交于 2019-11-29 11:22:19

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

You could use is_page() after template redirect so you need to add in the hook like this :

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

You must register your script as if you want it to work everywhere. You can de-register it after the job is done, like this:

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 );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!