Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PiotrKrzyzek/b24271f1493ed5d15979e1f5104af8d7 to your computer and use it in GitHub Desktop.
Save PiotrKrzyzek/b24271f1493ed5d15979e1f5104af8d7 to your computer and use it in GitHub Desktop.
WordPress shortcode for getting a list of categories (and the children, non-zero) for the given main category and print it out in a button list (for elementor)
<?php
function list_categories_and_children($atributes)
{
$atts = shortcode_atts(array(
'main' => null
), $atributes);
$cat_id = $atts['main'];
if (isset($atts['main'])) {
} else {
$cat = get_category(get_query_var('cat'));
$cat_id = $cat->cat_ID;
}
$child_categories = get_categories(
array(
'parent' => 30,
'hide_empty' => 0,
)
);
$category = get_queried_object();
$childCurrentClass = '';
$single_use_case_wrapper = '';
echo "<div class='category_filter_bar'><h5>Filter by:</h5>";
echo "<ul>";
if ($cat_id === 30) {
$single_use_case_wrapper = 'current_category ';
}
echo "<li class='generic_button_list_wrapper'><a class='" . $single_use_case_wrapper . "elementor-button elementor-size-lg' href='" . esc_url(get_category_link(30)) . "'>All</a></li>";
foreach ($child_categories as $child) {
if (isset($cat->cat_name)) {
if ($cat->cat_name === $child->cat_name) {
$childCurrentClass = 'current_category ';
} else {
$childCurrentClass = '';
}
}
echo "<li class='generic_button_list_wrapper'><a class='" . $childCurrentClass . "elementor-button elementor-size-lg' href='" . esc_url(get_category_link($child->term_id)) . "'>" . $child->cat_name . "</a></li>";
}
echo "</ul></div>";
return null;
}
add_shortcode('listcategories', 'list_categories_and_children');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment