下面的代码接近我的函数的顶部。php,并设置为仅在激活“我的主题”时运行:
if ( is_admin() && isset($_GET[\'activated\'] ) && $pagenow == \'themes.php\' ) {
然而,即使它创建了类别“my utilities”,它显然无法将category1和category2项的父项设置为新创建的类别。
也许对新创建的类别调用get\\u cat\\u id还为时过早?
我相信这与此有关,因为该类别在主题第二次激活时重新发布。我推测,这是因为将用作父级的类别之前已经创建,因此例程在查找其ID并将其用作category1和category2的父级时没有问题。
我错过了什么?
// with activate make sure theme\'s utility categories are present 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\');
if(!get_cat_ID(\'my-utilities\')){wp_create_category(\'my-utilities\');}
//find out the ID of the newly created category, "my-utilities"
$my_default_cat = my_cat();
if(!get_cat_ID(\'category1\')){wp_create_category(\'category1\',$my_default_cat);}
if(!get_cat_ID(\'category2\')){wp_create_category(\'category2\',$my_default_cat);}
//if the categories already existed, reparent them
$myCategory1[\'cat_ID\'] = get_cat_id(\'category1\');
$myCategory1[\'category_parent\'] = $my_default_cat;
wp_update_category($myCategory1);
$myCategory2[\'cat_ID\'] = get_cat_id(\'category2\');
$myCategory2[\'category_parent\'] = $my_default_cat;
wp_update_category($myCategory2);
}
}
//utility category
function my_cat()
{
if(get_cat_ID(\'my-utilities\'))
{
return get_cat_ID(\'my-utilities\');
}
else
{
if(term_exists(1)) return "1";
else return get_option(\'default_category\');
}
}
最合适的回答,由SO网友:Denis de Bernardy 整理而成
您正在查找以下内容:
register_activation_hook( __FILE__, \'your_plugin_activate_function_name\' );
编辑:对于主题,您可以使用以下内容:
$theme_version = get_option(\'my_theme_version\');
switch ((string) $theme_version) {
// an early alpha... run upgrade code
case \'0.1\':
// another version... run upgrade code
case \'0.5\':
// add other cases as needed... without any break statement.
// if we\'re here and in the admin area (to avoid race conditions),
// actually save whichever changes we did
if (is_admin()) {
update_option(\'my_theme_version\', \'1.0\');
// do other stuff
}
// we\'re at the latest version: bail here.
case \'1.0\':
break;
default:
// install code goes here
}