如何在插件中使用 is_page()? [英] How can I use is_page() inside a plugin?

查看:25
本文介绍了如何在插件中使用 is_page()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的插件仅在特定页面中注册脚本.

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

但我收到错误:

is_page 被错误地调用.条件查询标签不起作用在查询运行之前.在此之前,它们总是返回 false.请有关更多信息,请参阅在 WordPress 中调试.(这条消息是在 3.1 版中添加.)

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?

推荐答案

is_page() 仅适用于模板文件.

要在插件文件中使用它,您需要将它与 结合使用template_redirect 动作钩子.

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

这个动作钩子在 WordPress 决定加载哪个模板页面之前执行.

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

这篇关于如何在插件中使用 is_page()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆