Last active
November 9, 2023 13:53
-
-
Save diggeddy/4e426d6c9a326eb9871f16f11986af3d to your computer and use it in GitHub Desktop.
Custom show me the categories
This file contains 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
function category_list_with_images_shortcode($atts) { | |
$atts = shortcode_atts(array( | |
'parent_category' => '', // Default to empty (no specific parent category) | |
), $atts); | |
$parent_category = $atts['parent_category']; | |
if (empty($parent_category) && is_category()) { | |
// if no parent_category and is_category then use current term | |
$current_category = get_queried_object(); | |
$parent_category = $current_category->term_id; | |
} | |
$common_args = array( | |
'taxonomy' => 'category', | |
'hide_empty' => false, | |
'orderby' => 'name', | |
'order' => 'ASC', | |
); | |
// add parent if applicable | |
if (!empty($parent_category)) { | |
$common_args['child_of'] = $parent_category; | |
} | |
$categories = get_terms($common_args); | |
// sort our categories to account for sub-child heirarchical ordering. | |
$sorted_categories = array(); | |
foreach ($categories as $category) { | |
$sorted_categories[$category->term_id] = $category; | |
} | |
uasort($sorted_categories, function ($a, $b) { | |
return strcmp($a->name, $b->name); | |
}); | |
$output = '<ul class="category-grid">%s</ul>'; | |
$list_items = ''; // Initialize list items | |
if (!empty($sorted_categories)) { | |
foreach ($sorted_categories as $category) { | |
// Get the term image ID from the ACF field 'term_image' | |
$term_image_id = get_field('term_image', 'category_' . $category->term_id); | |
$term_link = get_term_link($category); | |
if (!empty($term_image_id) && !is_wp_error($term_link)) { | |
// Get the image URL from the image ID | |
$term_image = wp_get_attachment_image_url($term_image_id, 'full'); | |
if ($term_image) { | |
$list_items .= sprintf( | |
'<li class="category-term"><a href="%s"><img src="%s" alt="%s"><span class="cat-name">%s</span></a></li>', | |
esc_url($term_link), | |
esc_url($term_image), | |
esc_attr($category->name), | |
esc_html($category->name) | |
); | |
} | |
} | |
} | |
} | |
return sprintf($output, $list_items); | |
} | |
add_shortcode('category_list', 'category_list_with_images_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment