Currently we’re using wp_list_pages
to show a list of child pages. However, we’d like to get the category of each page, and display some CSS on the front-end based on what category each page is in. This is the query we’re currently using:
wp_list_pages( 'post_status=publish&post_type=board-meetings&title_li=' );
Is there a way of of getting the category of each page?
Currently we’re using wp_list_pages
to show a list of child pages. However, we’d like to get the category of each page, and display some CSS on the front-end based on what category each page is in. This is the query we’re currently using:
wp_list_pages( 'post_status=publish&post_type=board-meetings&title_li=' );
Is there a way of of getting the category of each page?
Share Improve this question edited Mar 12, 2019 at 14:51 Howdy_McGee♦ 20.9k24 gold badges91 silver badges177 bronze badges asked Mar 12, 2019 at 11:33 June CooperJune Cooper 12 bronze badges1 Answer
Reset to default 0You can get an array of pages using get_pages()
and then for each page retrieve categories using wp_get_object_terms
. Your code may look like this:
$args = array(
'post_type' => 'board-meeting',
'post_status' => 'publish'
);
$pages = get_pages($args);
if ( ! empty( $pages ) ) {
echo '<ul>';
foreach($pages as $page){
$cats = wp_get_object_terms( $page->ID, 'category' ); // Array of categories
$cat = '';
if ( ! empty( $cats ) ) {
if ( ! is_wp_error( $cats ) ) {
$cat = $cats[0]->slug; // slug of 1st category in the array $cats
}
// slug of category used as CSS class name for anchor tag
echo '<li><a class='. $cat.' href="' . get_permalink($page-ID) . '">' . esc_html( $page->post_title ) . '</a></li>';
}
}
echo '</ul>';
}
You may adjust the code to your needs.
I hope this helps.