Fetch Post Category

If you want to display and fetch all post categories that have posts associated with them and display them in a dropdown list in the WP admin panel, try below the code add in code to your themes functions.php file or in a custom plugin.

function get_categories_with_posts() {
    // Get all categories that have posts
    $categories = get_categories(array(
        'hide_empty' => false, // Include categories with no posts
        'orderby' => 'name',
        'order' => 'ASC'
    ));

    $options = array();

    foreach ($categories as $category) {
        $options[$category->term_id] = $category->name;
    }

    return $options;
}

function add_category_dropdown_to_admin_panel() {
    // Get categories with posts
    $categories = get_categories_with_posts();

    // Display the dropdown list
    ?>
    <select name="post_category" id="post_category">
        <option value="">Select Category</option>
        <?php foreach ($categories as $id => $name) : ?>
            <option value="<?php echo esc_attr($id); ?>"><?php echo esc_html($name); ?></option>
        <?php endforeach; ?>
    </select>
    <?php
}

// Add the dropdown to the admin panel
function add_category_dropdown_to_admin_panel_hook() {
    add_meta_box(
        'category_dropdown',
        'Post Category',
        'add_category_dropdown_to_admin_panel',
        'post',
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'add_category_dropdown_to_admin_panel_hook');