Last active
April 10, 2025 17:54
-
-
Save cccamuseme/84d80b680d330a8a6df1f6e8c9c906b4 to your computer and use it in GitHub Desktop.
Create Custom Page Taxonomy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create Page Category Custom Taxonomy (page post type) | |
function register_page_category_taxonomy() { | |
register_taxonomy('page_category', 'page', [ | |
'label' => 'Page Categories', | |
'public' => true, | |
'hierarchical' => true, | |
'show_ui' => true, | |
'show_admin_column' => true, | |
]); | |
} | |
add_action('init', 'register_page_category_taxonomy'); | |
// Add Filter Dropdown to Admin List Table (page post type) | |
function add_page_category_filter_to_admin() { | |
global $typenow; | |
if ($typenow === 'page') { | |
$taxonomy = 'page_category'; | |
$taxonomy_obj = get_taxonomy($taxonomy); | |
$terms = get_terms([ | |
'taxonomy' => $taxonomy, | |
'hide_empty' => false, | |
]); | |
if (!empty($terms)) { | |
echo '<select name="' . esc_attr($taxonomy) . '" class="postform">'; | |
echo '<option value="">' . esc_html($taxonomy_obj->labels->all_items) . '</option>'; | |
foreach ($terms as $term) { | |
$selected = (!empty($_GET[$taxonomy]) && $_GET[$taxonomy] == $term->slug) ? ' selected="selected"' : ''; | |
echo '<option value="' . esc_attr($term->slug) . '"' . $selected . '>' . esc_html($term->name) . '</option>'; | |
} | |
echo '</select>'; | |
} | |
} | |
} | |
add_action('restrict_manage_posts', 'add_page_category_filter_to_admin'); | |
// Modify the Query to Filter by Selected Term | |
function filter_pages_by_page_category($query) { | |
global $pagenow; | |
if ($pagenow === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'page' && isset($_GET['page_category']) && $_GET['page_category'] !== '') { | |
$query->query_vars['tax_query'] = [[ | |
'taxonomy' => 'page_category', | |
'field' => 'slug', | |
'terms' => $_GET['page_category'], | |
]]; | |
} | |
} | |
add_filter('pre_get_posts', 'filter_pages_by_page_category'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment