Plugin for creating an submenu in wordpress

Insert the below code as a plugin in WordPress.

code:

<?php
/*
Plugin Name: Custom Department Plugin
Description: Adds a custom menu for departments.
Version: 1.0
Author: Mukil Mukesh M K
*/
function custom_department_menu() {
    add_menu_page(
        'Departments',
        'Departments',
        'manage_options',
        'custom_department_menu',
        'custom_department_page'
    );
}
add_action('admin_menu', 'custom_department_menu');


function save_department_to_database($name, $description, $head_user_id) {
    // Sanitize data
    $name = sanitize_text_field($name);
    $description = sanitize_text_field($description);


    // Get existing departments
    $departments = get_option('all_departments', array());


    // Add the new department
    $departments[] = array(
        'name' => $name,
        'description' => $description,
        'head_user_id' => $head_user_id,
    );


    // Update option with all departments
    update_option('all_departments', $departments);


    return true;
}


function delete_department_from_database($index) {
    // Get existing departments
    $departments = get_option('all_departments', array());


    // Remove the department at the specified index
    unset($departments[$index]);


    // Re-index the array
    $departments = array_values($departments);


    // Update option with modified departments
    update_option('all_departments', $departments);


    return true;
}


function update_department_in_database($index, $name, $description, $head_user_id) {
    // Get existing departments
    $departments = get_option('all_departments', array());


    // Update the department at the specified index
    $departments[$index]['name'] = sanitize_text_field($name);
    $departments[$index]['description'] = sanitize_text_field($description);
    $departments[$index]['head_user_id'] = $head_user_id;


    // Update option with modified departments
    update_option('all_departments', $departments);


    return true;
}


function display_departments_table() {
    // Retrieve all departments
    $departments = get_option('all_departments', array());


    if (!empty($departments)) {
        echo '<table id="departments_table" style="margin-left:10%; width: 80%; border-collapse: collapse; margin-top: 20px;">';
        echo '<tr style="background-color: #f2f2f2;"><th style="padding: 10px; border: 1px solid #ddd;">Department Name</th><th style="padding: 10px; border: 1px solid #ddd;">Description</th><th style="padding: 10px; border: 1px solid #ddd;">Head User</th><th style="padding: 10px; border: 1px solid #ddd;">Actions</th></tr>';
        foreach ($departments as $index => $department) {
            $row_color = ($index % 2 == 0) ? 'background-color: #f9f9f9;' : ''; // Grey background for even-numbered rows
            echo '<tr style="' . $row_color . '">';
            echo '<td style="padding: 10px; border: 1px solid #ddd;">' . esc_html($department['name']) . '</td>';
            echo '<td style="padding: 10px; border: 1px solid #ddd;">' . esc_html($department['description']) . '</td>';
            echo '<td style="padding: 10px; border: 1px solid #ddd;">' . esc_html(get_user_by('id', $department['head_user_id'])->display_name) . '</td>';
            echo '<td style="padding: 10px; border: 1px solid #ddd;"><button class="edit-department" data-index="' . $index . '" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
            white-space: nowrap;
            text-decoration: none;
            text-shadow: none;
            top: 5px;
            margin-left: 4px;
            border: 1px solid #2271b1;
            border-radius: 3px;
            background: #f6f7f7;
            font-size: 13px;
            font-weight: 400;
            line-height: 2.15384615;
            color: #2271b1;
            padding: 0 10px;
            min-height: 30px;
            -webkit-appearance: none;">Edit</button><button class="delete-department" data-index="' . $index . '" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
            white-space: nowrap;
            text-decoration: none;
            text-shadow: none;
            top: 5px;
            margin-left: 4px;
            border: 1px solid #2271b1;
            border-radius: 3px;
            background: #f6f7f7;
            font-size: 13px;
            font-weight: 400;
            line-height: 2.15384615;
            color: #2271b1;
            padding: 0 10px;
            min-height: 30px;
            -webkit-appearance: none;">Delete</button></td>';
            echo '</tr>';
        }
        echo '</table>';
    } else {
        echo '<p style="margin-left:10%">No departments found.</p>';
    }
}


function custom_department_page() {
    // Check if the form is submitted
    if (isset($_POST['save_department'])) {
        // Get form values
        $department_name = sanitize_text_field($_POST['department_name']);
        $department_description = sanitize_text_field($_POST['department_description']);
        $head_user_id = intval($_POST['user_select']);


        // Insert the new department into the database
        $result = save_department_to_database($department_name, $department_description, $head_user_id);


        // Display a success or error message
        if ($result) {
            echo '<p class="notice is-dismissible updated" style="padding: 10px;">Department saved successfully!</p>';
        } else {
            echo '<p>Error saving department. Please try again.</p>';
        }
    }


    // Check if delete button is clicked
    if (isset($_POST['delete_department'])) {
        // Get the index of the department to be deleted
        $delete_index = intval($_POST['delete_department']);
        // Delete the department from the database
        $result = delete_department_from_database($delete_index);
        // Display a success or error message
        if ($result) {
            echo '<p class="notice is-dismissible updated" style="padding: 10px;">Department deleted successfully!</p>';
        } else {
            echo '<p>Error deleting department. Please try again.</p>';
        }
    }


    // Check if edit form is submitted
    if (isset($_POST['save_edited_department'])) {
        // Get form values
        $edited_department_name = sanitize_text_field($_POST['edited_department_name']);
        $edited_department_description = sanitize_text_field($_POST['edited_department_description']);
        $edited_head_user_id = intval($_POST['edited_head_user_id']);
        $edit_department_index = intval($_POST['edit_department_index']);


        // Update the department in the database
        $result = update_department_in_database($edit_department_index, $edited_department_name, $edited_department_description, $edited_head_user_id);


        // Display a success or error message
        if ($result) {
            echo '<p class="notice is-dismissible updated" style="padding: 10px;">Department updated successfully!</p>';
        } else {
            echo '<p>Error updating department. Please try again.</p>';
        }
    }


    // Get existing departments
    $departments = get_option('all_departments', array());


    // Convert PHP array to JSON
    $departments_json = json_encode($departments);
    ?>


    <div class="department-div" style="display:flex">
        <h1>Departments</h1>
        <!-- Create Button -->
        <button id="create_department_button" class="page-title-action" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
			height: 30px;
            white-space: nowrap;
            text-decoration: none;
            text-shadow: none;
            top: 5px;
            margin-left: 4px;
            border: 1px solid #2271b1;
            border-radius: 3px;
            background: #f6f7f7;
            font-size: 13px;
            font-weight: 400;
            line-height: 2.15384615;
            color: #2271b1;
            padding: 0 10px;
            min-height: 30px;
            -webkit-appearance: none;">Create Department</button>
    </div>


    <!-- Form for Creating Department (Initially hidden) -->
    <div id="create_department_form" style="display: none;">
        <h2>Create Department</h2>
        <form method="post" action="">
            <div class="department-div" style="display: grid; width: 50%;">		
                <label for="department_name" style="margin-bottom: 10px;">Department:</label>
                <input type="text" name="department_name" required style="margin-bottom: 20px;">


                <label for="department_description" style="margin-bottom: 10px;">Description:</label>
                <textarea name="department_description" rows="5" cols="30" placeholder="optional" style="resize:none; margin-bottom: 10px;"></textarea>


                <label for="user_select" style="margin-bottom: 10px;">Select Head:</label>
                <?php
                // Use wp_dropdown_users to display a dropdown of all users
                wp_dropdown_users(array(
                    'name' => 'user_select',
                    'show_option_all' => 'Select Head',
                ));
                ?>
            </div>
            <div style="margin-top: 10px;">
                <input type="submit" name="save_department" value="Create" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
			height: 30px;
            white-space: nowrap;
            text-decoration: none;
            text-shadow: none;
            top: 5px;
            margin-left: 4px;
            border: 1px solid #2271b1;
            border-radius: 3px;
            background: #f6f7f7;
            font-size: 13px;
            font-weight: 400;
            line-height: 2.15384615;
            color: #2271b1;
            padding: 0 10px;
            min-height: 30px;
            -webkit-appearance: none;">
                <button type="button" id="cancel_create_department" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
			height: 30px;
            white-space: nowrap;
            text-decoration: none;
            text-shadow: none;
            top: 5px;
            margin-left: 4px;
            border: 1px solid #2271b1;
            border-radius: 3px;
            background: #f6f7f7;
            font-size: 13px;
            font-weight: 400;
            line-height: 2.15384615;
            color: #2271b1;
            padding: 0 10px;
            min-height: 30px;
            -webkit-appearance: none;">Cancel</button>
            </div>
        </form>
    </div>
    <div id="edit_department_modal" style="display: none;">
        <h2>Edit Department</h2>
        <form method="post" action="">
            <div class="edit-department-div" style="display: grid; width: 50%;">
                <label for="edited_department_name" style="margin-bottom: 10px;">Department:</label>
                <input type="text" name="edited_department_name" id="edited_department_name" required style="margin-bottom: 20px;">


                <label for="edited_department_description" style="margin-bottom: 10px;">Description:</label>
                <textarea name="edited_department_description" id="edited_department_description" rows="5" cols="30" style="resize:none; margin-bottom: 20px;"></textarea>


                <label for="edited_department_head" style="margin-bottom: 10px;">Select Head:</label>
                <?php
				// Use wp_dropdown_users to display a dropdown of all users
// Use wp_dropdown_users to display a dropdown of all users
wp_dropdown_users(array(
    'name' => 'edited_head_user_id',
    'show_option_all' => 'Select Head',
    'selected' => $departments[$edit_department_index]['head_user_id'], // Set the selected user based on the department being edited
));




	
                ?>
            </div>
            <input type="hidden" name="edit_department_index" id="edit_department_index">
            <input type="submit" name="save_edited_department" value="Save Changes" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
                height: 30px;
                white-space: nowrap;
                text-decoration: none;
                text-shadow: none;
                top: 5px;
                margin-left: 4px;
                border: 1px solid #2271b1;
                border-radius: 3px;
                background: #f6f7f7;
                font-size: 13px;
                font-weight: 400;
                line-height: 2.15384615;
                color: #2271b1;
                padding: 0 10px;
                min-height: 30px;
                -webkit-appearance: none;">
            <button id="close_edit_department_modal" style="border-color: #183ad6; display: inline-block; position: relative; box-sizing: border-box; cursor: pointer;
                height: 30px;
                white-space: nowrap;
                text-decoration: none;
                text-shadow: none;
                top: 5px;
                margin-left: 4px;
                border: 1px solid #2271b1;
                border-radius: 3px;
                background: #f6f7f7;
                font-size: 13px;
                font-weight: 400;
                line-height: 2.15384615;
                color: #2271b1;
                padding: 0 10px;
                min-height: 30px;
                -webkit-appearance: none;">Close</button>
        </form>
    </div>


    <?php
    // Display all departments in a table
    display_departments_table();
    ?>
<script>
		// JavaScript to handle delete button click
var deleteButtons = document.getElementsByClassName('delete-department');
for (var i = 0; i < deleteButtons.length; i++) {
    deleteButtons[i].addEventListener('click', function () {
        var index = this.getAttribute('data-index');
        if (confirm('Are you sure you want to delete this department?')) {
            // Create a form element
            var form = document.createElement('form');
            form.method = 'post';
            form.action = '';


            // Create an input element for the delete action
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'delete_department';
            input.value = index;


            // Append the input element to the form
            form.appendChild(input);


            // Append the form to the document body
            document.body.appendChild(form);


            // Submit the form
            form.submit();
        }
    });
}
// JavaScript to handle cancel button click in the create form
document.getElementById('cancel_create_department').addEventListener('click', function () {
    var table = document.getElementById('departments_table');
    var createForm = document.getElementById('create_department_form');
    var createButton = document.getElementById('create_department_button');


    if (table) {
        table.style.display = table.dataset.originalDisplay || 'table'; // Restore the original display style or default to 'table'
    }


    if (createForm) {
        // Clear input and textarea fields manually
        var inputField = createForm.querySelector('input[name="department_name"]');
        var textareaField = createForm.querySelector('textarea[name="department_description"]');


        if (inputField) {
            inputField.value = '';
        }


        if (textareaField) {
            textareaField.value = '';
        }


        createForm.style.display = 'none'; // Hide the form
    }


    if (createButton) {
        createButton.style.display = 'inline-block'; // Show the Create department button
    }


    // Hide the "No departments found" message
    var noDepartmentsMessage = document.getElementById('no_department_message');
    if (noDepartmentsMessage) {
        noDepartmentsMessage.style.display = 'none';
    }
});




// JavaScript to handle button click and show the form
document.getElementById('create_department_button').addEventListener('click', function () {
    var table = document.getElementById('departments_table');
    var createForm = document.getElementById('create_department_form');
    var createButton = document.getElementById('create_department_button');


    if (table) {
        table.dataset.originalDisplay = table.style.display; // Remember the original display style
        table.style.display = 'none'; // Hide the table
    }


    if (createForm) {
        createForm.style.display = 'block';
    }


    if (createButton) {
        createButton.style.display = 'none'; // Hide the Create department button
    }


    // Hide the "No departments found" message
    var noDepartmentsMessage = document.getElementById('no_departments_message');
    if (noDepartmentsMessage) {
        noDepartmentsMessage.style.display = 'none';
    }
});






        // JavaScript to handle cancel button click in the create form
        document.getElementById('cancel_create_department').addEventListener('click', function () {
            var table = document.getElementById('departments_table');
            table.style.display = table.dataset.originalDisplay; // Restore the original display style
            document.getElementById('create_department_form').style.display = 'none'; // Hide the form
            document.getElementById('create_department_button').style.display = 'inline-block'; // Show the Create department button
        });


// JavaScript to handle edit button click and show the edit modal with existing data
var editButtons = document.getElementsByClassName('edit-department');
for (var i = 0; i < editButtons.length; i++) {
    editButtons[i].addEventListener('click', function () {
        var index = this.getAttribute('data-index');
        var table = document.getElementById('departments_table');
        table.dataset.originalDisplay = table.style.display; // Remember the original display style
        table.style.display = 'none'; // Hide the table


        // Parse the JSON object
        var departments = <?php echo $departments_json; ?>;
        var name = departments[index].name;
        var description = departments[index].description;
        var headUserId = departments[index].head_user_id;


        document.getElementById('edited_department_name').value = name;
        document.getElementById('edited_department_description').value = description;
        document.getElementById('edited_head_user_id').value = headUserId; // Set the selected head user ID
        document.getElementById('edit_department_index').value = index;
        document.getElementById('edit_department_modal').style.display = 'block';
        
        // Hide the Create department button when the edit modal is open
        document.getElementById('create_department_button').style.display = 'none';
    });
}




        // JavaScript to handle closing the modal and showing the table again
        document.getElementById('close_edit_department_modal').addEventListener('click', function () {
            var table = document.getElementById('departments_table');
            table.style.display = table.dataset.originalDisplay; // Restore the original display style
            document.getElementById('edit_department_modal').style.display = 'none';
            
            // Show the Create department button when the edit modal is closed
            document.getElementById('create_department_button').style.display = 'inline-block';
        });
    </script>


<?php
}
?>

Screenshot:

When the department submenu is clicked there will be a button for creating a new department as shown in the image:

Leave a comment

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