Wordpress 什么';这个函数有什么问题?尝试仅在主题激活上运行代码

Wordpress 什么';这个函数有什么问题?尝试仅在主题激活上运行代码,wordpress,Wordpress,下面的函数应该在它所属的主题被激活时启动。然而,为了让它在条件中实际创建类别,我必须(1)激活主题,(2)激活任何其他主题(3)再次激活主题 它应该在第一次激活时进行处理 // with activate make sure utility categories are created and parented correctly if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'theme

下面的函数应该在它所属的主题被激活时启动。然而,为了让它在条件中实际创建类别,我必须(1)激活主题,(2)激活任何其他主题(3)再次激活主题

它应该在第一次激活时进行处理

// with activate make sure utility categories are created and parented correctly
if ( is_admin() && isset($_GET['activated'] ) && $pagenow == 'themes.php' ) {

    if (file_exists(ABSPATH.'/wp-admin/includes/taxonomy.php'))
    {
        require_once(ABSPATH.'/wp-admin/includes/taxonomy.php');    

        wp_create_category('nofollow');
        $myCategory1['cat_ID'] = get_cat_id('nofollow');
        $myCategory1['category_parent'] = 1;
        wp_update_category($myCategory1);

        wp_create_category('noindex');
        $myCategory2['cat_ID'] = get_cat_id('noindex');
        $myCategory2['category_parent'] = 1;
        wp_update_category($myCategory2);

    }
}

我在你的另一个问题中回答了这个问题,然后在这里看到了。希望同样的答案也适用于你的重新激活难题。尝试使用这个钩子而不是$\u GET请求,也许您需要将其作为插件,而不是将其放在functions.php文件中,以便在激活主题时运行它。先前的答复如下:

您将需要使用动作挂钩。特别是“切换主题”。这是的codex页面,我无法链接到switch_主题,但向下滚动,您会找到它。关于这个钩子没有具体的信息,但是用法很简单。您可以将函数包含在functions.php或插件文件中,并在函数定义后包括:

在wordpress中遇到命名钩子时,“add_action()”调用将运行命名函数。“切换主题”钩子在主题更改后运行

重要的是要知道,这个钩子将为您的函数提供新的当前主题的名称,如果您需要,它可以接受它作为参数。例如,确保仅当您的主题是激活的主题时才运行该函数。我想如果这个函数在你的theme的functions.php文件中,它将永远不会运行,除非你的主题被激活,所以你可以决定是否需要再次检查主题名

function add_my_categories($my-theme-name){
        //if $my-theme-name == 'my_theme_name
            //test if category exists
            //if exists, update
            //if doesn't exist, create and assign parent
    }
add_action('switch_theme','add_my_categories');