• How to fetch all post categories which has posts and show in a drop down list in WordPress Admin panel ?

    • This topic was modified 7 months, 4 weeks ago by mabufoysal.
Viewing 1 replies (of 1 total)
  • // Add custom meta box
    function custom_post_category_dropdown_meta_box() {
        add_meta_box(
            'custom-post-category-dropdown',
            __('Post Category Dropdown', 'textdomain'),
            'custom_post_category_dropdown_meta_box_callback',
            'post', // change to your post type if needed
            'side',
            'default'
        );
    }
    add_action('add_meta_boxes', 'custom_post_category_dropdown_meta_box');
    // Meta box callback function
    function custom_post_category_dropdown_meta_box_callback($post) {
        // Fetch categories with posts
        $categories = get_categories(array(
            'hide_empty' => 0,
            'orderby' => 'name',
            'order' => 'ASC'
        ));
    
        // Dropdown list HTML
        echo '<label for="custom-post-category">Select Category:</label><br>';
        echo '<select id="custom-post-category" name="custom_post_category">';
        echo '<option value="">Select Category</option>';
        foreach ($categories as $category) {
            echo '<option value="' . $category->slug . '">' . $category->name . '</option>';
        }
        echo '</select>';
    }
    // Save custom meta box data
    function save_custom_post_category_dropdown_meta_box_data($post_id) {
        if (array_key_exists('custom_post_category', $_POST)) {
            update_post_meta(
                $post_id,
                '_custom_post_category',
                $_POST['custom_post_category']
            );
        }
    }
    add_action('save_post', 'save_custom_post_category_dropdown_meta_box_data');

    Hope this will serve the purpose, if you php and wordpress knowledge you can customize as your need/

Viewing 1 replies (of 1 total)
  • The topic ‘Category drop down list’ is closed to new replies.