Skip to content

Instantly share code, notes, and snippets.

@khoipro
Created November 15, 2019 09:10
Show Gist options
  • Select an option

  • Save khoipro/6ac0f09556b461b5e4ab0619160d7803 to your computer and use it in GitHub Desktop.

Select an option

Save khoipro/6ac0f09556b461b5e4ab0619160d7803 to your computer and use it in GitHub Desktop.
WordPress: Helper functions to get first category's metadata.
<?php
function your_theme_prefix_get_first_cat_object($page_id, $category_metadata) {
if ( empty($page_id) ) {
return new WP_Error('404', __('Missing $page_id parameter', 'your_theme_prefix'), array());
}
$categories = get_the_category($page_id);
return !empty($categories) ? $categories[0]->{$category_metadata} : null;
}
function your_theme_prefix_get_category_slug($page_id) {
return your_theme_prefix_get_first_cat_object($page_id, 'slug');
}
function your_theme_prefix_get_category_name($page_id) {
return your_theme_prefix_get_first_cat_object($page_id, 'name');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment