在unctions.php中的函数内部不起作用的函数

时间:2021-08-31 作者:Hashim Aziz

根据Christine的回答,我有以下功能here 它可以在Gutenberg编辑器中完全隐藏面板/元盒:

function irm_gutenberg_register_files() {
    wp_register_script(
        \'cc-block-script\',
        get_stylesheet_directory_uri() . \'/functions.js\', // adjust the path to the JS file
        array(\'wp-blocks\', \'wp-edit-post\')
    );

    // register block editor script
    register_block_type(\'cc/ma-block-files\', array(
        \'editor_script\' => \'cc-block-script\'
    ));
}
add_action(\'init\', \'irm_gutenberg_register_files\');
但是,当我尝试将此函数移动到更大的函数时,它会停止工作:

function irm_lockdown_author_role() {

if (isset($userrole->roles[0])) {
    $current_role = $userrole->roles[0];
} else {
    $current_role = \'no_role\';
}

if (\'author\' == $current_role) {

...

        function irm_gutenberg_register_files() {
            wp_register_script(
                \'cc-block-script\',
                get_stylesheet_directory_uri() . \'/functions.js\', // adjust the path to the JS file
                array(\'wp-blocks\', \'wp-edit-post\')
            );

            // register block editor script
            register_block_type(\'cc/ma-block-files\', array(
                \'editor_script\' => \'cc-block-script\'
            ));
        }
        add_action(\'init\', \'irm_gutenberg_register_files\');

    }
}

add_action(\'init\', \'irm_lockdown_author_role\');
除此函数外,较大函数中的其他所有内容都可以正常运行。这里发生了什么事,我该怎么解决?

1 个回复
最合适的回答,由SO网友:Lee 整理而成

移除函数中的函数,并调用wp_register_scriptregister_block_type 大功能内部。

最后,拆下内部add_action() 调用,因此您只有大函数的结尾。

function irm_lockdown_author_role() {

if (isset($userrole->roles[0])) {
    $current_role = $userrole->roles[0];
} else {
    $current_role = \'no_role\';
}

if (\'author\' == $current_role) {

        /* function irm_gutenberg_register_files() { */
            wp_register_script(
                \'cc-block-script\',
                get_stylesheet_directory_uri() . \'/functions.js\', // adjust the path to the JS file
                array(\'wp-blocks\', \'wp-edit-post\')
            );

            // register block editor script
            register_block_type(\'cc/ma-block-files\', array(
                \'editor_script\' => \'cc-block-script\'
            ));
        /* }
        add_action(\'init\', \'irm_gutenberg_register_files\'); */

    }
}

add_action(\'init\', \'irm_lockdown_author_role\');

相关推荐

如何在Reaction JS/Gutenberg中使用wp.hooks.addAction()?

我能够成功使用wp.hooks.applyFilters() 和wp.hooks.addFilter(), 但我无法使用wp.hooks.addAction(). 但是console.log() 在某个操作的回调中运行良好。这是我的代码:import { createHooks } from \'@wordpress/hooks\'; let globalHooks = createHooks(); const Header = () => { r