Skip to content

Instantly share code, notes, and snippets.

@vovadocent
Last active February 10, 2023 16:08
Show Gist options
  • Save vovadocent/d568c848906700ab0c5385d37531806c to your computer and use it in GitHub Desktop.
Save vovadocent/d568c848906700ab0c5385d37531806c to your computer and use it in GitHub Desktop.
WP Register custom post types/taxonomies from arrays
<?php
/**
* Custom Post Types and Taxonomies
*/
function vd_register_custom_post_type()
{
$post_types = [
'faq' => [
'name' => 'FAQ',
'p_name' => 'FAQs',
'args' => [
'capability_type' => 'post',
'public' => false,
'show_ui' => true,
'show_in_rest' => true,
'menu_position' => 55,
]
],
];
foreach ($post_types as $post_type => $cpt) {
$name = $cpt['name'];
$p_name = $cpt['p_name'];
$args = $cpt['args'];
$def_args = [
'public' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'hierarchical' => false,
'rewrite' => [ 'with_front' => false ],
'has_archive' => false,
'menu_icon' => 'dashicons-lightbulb',
'capability_type' => 'post',
'labels' => [
'name' => $p_name,
'singular_name' => $name,
'add_new' => "Add New $name",
'add_new_item' => "Add New $name",
'edit_item' => "Edit $name",
'new_item' => "New $name",
'all_items' => $p_name,
'view_item' => "View $p_name",
'search_items' => "Search $p_name",
'not_found' => 'Not found',
'not_found_in_trash' => 'No found in Trash',
'parent_item_colon' => '',
'menu_name' => $p_name
]
];
register_post_type($post_type, array_replace($def_args, $args));
}
$taxonomies = [
'faq_category' => [
'name' => 'Category',
'p_name' => 'Categories',
'post_type' => 'faq',
'args' => [
'public' => false,
'show_ui' => true,
'show_in_rest' => false,
'show_admin_column' => true,
]
],
];
foreach ($taxonomies as $taxonomy => $cpt) {
$name = $cpt['name'];
$p_name = $cpt['p_name'];
$args = $cpt['args'];
$post_type = $cpt['post_type'];
$def_args = [
'public' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'hierarchical' => false,
'show_admin_column' => false,
'rewrite' => [ 'with_front' => false ],
'has_archive' => false,
'menu_icon' => 'dashicons-portfolio',
'labels' => [
'name' => $p_name,
'singular_name' => $name,
'add_new' => "Add New $name",
'add_new_item' => "Add New $name",
'edit_item' => "Edit $name",
'new_item' => "New $name",
'all_items' => $p_name,
'view_item' => "View $p_name",
'search_items' => "Search $p_name",
'not_found' => 'Not found',
'not_found_in_trash' => 'No found in Trash',
'parent_item_colon' => '',
'menu_name' => $p_name
]
];
register_taxonomy($taxonomy, $post_type, array_replace($def_args, $args));
}
}
add_action('init', 'vd_register_custom_post_type', 20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment