我想,您的代码中的作用域有问题,并且您误用了操作。
让我解释一下。。。让我们看看这部分代码:
for($i =1; $i <= $options_foo[\'num_post_types\']; $i++) {
global $options_foo;
$singular = $options_foo[\'post_type_names\'][$i][\'singular\'];
$plural = $options_foo[\'post_type_names\'][$i][\'plural\'];
add_action(\'init\', function(){
global $singular;
它的作用是:
循环遍历所有选项,并针对其中的每一个选项:a)设置一些全局变量b)注册新操作init
挂钩所以过了一段时间init
使您的操作被逐一调用。但所有这些操作都将使用相同的全局变量值(因为它们早在…之前就设置好了)
下面是应该如何做:
add_action( \'init\', function () {
global $options_foo;
if ( $options_foo[\'num_post_types\'] > 0 ) {
for ( $i=1; $i <= $options_foo[\'num_post_types\']; $i++) {
$singular = $options_foo[\'post_type_names\'][$i][\'singular\'];
$plural = $options_foo[\'post_type_names\'][$i][\'plural\'];
$labels = array(
\'name\' => $plural,
\'singular_name\' => $singular,
\'add_new\' => "New $singular",
\'add_new_item\' => "New $singular",
\'edit_item\' => "Edit $singular",
\'new_item\' => "New $singular",
\'view_item\' => "View $singular",
\'view_items\' => "View $plural",
\'search_items\' => "Search $plural",
"not_found" => "No $plural Found",
"not_found_in_trash" => "No $plural Found in Trash",
\'all_items\' => "All $plural",
\'attributes\' => "$singular Attributes",
\'insert_into_item\' => "Insert to $singular",
\'uploaded_to_this_item\' => "Uploaded to this $singular"
);
$supports = array(\'title\', \'thumbnail\');
$args = array(
\'labels\' => $labels,
\'public\' => true,
\'exclude_from_search\' => true,
\'publicly_queryable\' => true,
\'show_in_nav_menus\' => false,
\'show_in_admin_bar\' => false,
\'menu_position\' => 5,
\'menu_icon\' => \'dashicons-admin-home\',
\'supports\' => $supports,
\'can_export\' => \'true\'
);
register_post_type($singular, $args);
}
}
});