儿童故事和童话

儿童故事、童话、睡前故事。

<?php

function level2_name_and_children_shortcode() {
    $output = '';

    // 获取所有分类
    $all_categories = get_categories(array(
        'hide_empty' => true
    ));

    foreach ($all_categories as $category) {
        // 判断是否是第二级分类(父是顶级)
        $parent_id = $category->parent;
        if ($parent_id == 0) continue;

        $grandparent = get_category($parent_id);
        if ($grandparent && $grandparent->parent != 0) continue;

        // 第二级分类加链接,但不加样式
        $output .= '<p><strong><a href="' . esc_url(get_category_link($category->term_id)) . '">' . esc_html($category->name) . '</a>:</strong>';

        // 获取其子分类
        $children = get_categories(array(
            'child_of' => $category->term_id,
            'hide_empty' => true
        ));

        if (!empty($children)) {
            foreach ($children as $child) {
                $output .= '<a href="' . esc_url(get_category_link($child->term_id)) . '" style="display: inline-block; background: #f5f5f5; border: 1px solid #ddd; padding: 5px 6px; margin: 5px 5px 0 0; border-radius: 4px; text-decoration: none; color: #333; font-size: 0.97rem; font-weight: bold;">' . esc_html($child->name) . '</a>';
            }
        } else {
            $output .= '(无子分类)';
        }

        $output .= '</p>';
    }

    return $output;
}
add_shortcode('level2_name_and_children', 'level2_name_and_children_shortcode');



error: Content is protected.