How can I use is_page() inside a plugin?

后端 未结 3 1236
青春惊慌失措
青春惊慌失措 2020-12-18 07:48

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())          


        
3条回答
  •  旧巷少年郎
    2020-12-18 08:37

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

提交回复
热议问题