Step 1: Create a Shortcode to List Categories

Add the following code to your theme’s functions.php file or a custom plugin:

// Function to display categories list
function display_categories_list_shortcode($atts) {
    // Extract shortcode attributes
    $atts = shortcode_atts(array(
        'orderby' => 'name', // Order by name
        'order' => 'ASC', // Ascending order
        'hide_empty' => 1, // Hide empty categories
        'show_count' => 0, // Show post count
    ), $atts, 'categories_list');

    // Get the categories
    $args = array(
        'orderby' => $atts['orderby'],
        'order' => $atts['order'],
        'hide_empty' => $atts['hide_empty'],
    );
    $categories = get_categories($args);

    // Initialize output
    $output = '<ul class="categories-list">';

    // Loop through categories and generate list items
    foreach ($categories as $category) {
        $output .= '<li>';
        $output .= '<a href="' . esc_url(get_category_link($category->term_id)) . '">' . esc_html($category->name) . '</a>';
        if ($atts['show_count']) {
            $output .= ' (' . $category->count . ')';
        }
        $output .= '</li>';
    }

    // Close the list
    $output .= '</ul>';

    // Return the output
    return $output;
}
add_shortcode('categories_list', 'display_categories_list_shortcode');

Step 2: Usage of Shortcode

[categories_list]

[categories_list orderby="count" order="DESC" show_count="1"]

[categories_list hide_empty="0"]

Step 3: Style the Categories List (Optional)

.categories-list {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.categories-list li {
    margin: 5px 0;
}

.categories-list li a {
    text-decoration: none;
    color: #0073aa;
}

.categories-list li a:hover {
    text-decoration: underline;
    color: #005177;
}

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *