Sunday, December 7, 2025

17 Auto pages Manu

 Prompt:

can you create plugin to add menu at top for pages like login, contactus, tutorials, projects, equivalence. Create the above pages with some sample text. Add the page background as lucid dark theme radiant and add contrast some sample content text

Here is a single-file WordPress plugin that:

  • Creates top menu with pages: Login, ContactUs, Tutorials, Projects, Equivalence

  • Auto-creates these pages with sample text

  • Applies a lucid dark radiant background and contrasting text through plugin-injected CSS

  • Keeps the code clean and simple


WordPress Plugin: Auto Menu + Pages + Dark Theme Background

Create a folder:

wp-content/plugins/auto-menu-pages

Inside it create a file:

auto-menu-pages.php

Paste the following:

<?php
/*
Plugin Name: Auto Menu & Sample Pages
Description: Creates top menu with sample pages and applies dark radiant background.
Version: 1.0 Dated 6.12.2025
Author: RMC
*/

// Create pages on activation
function amp_create_pages() {
    $pages = [
        'Login' => 'This is the login page. Add your form here.',
        'ContactUs' => 'This is the contact page. Students can reach you here.',
        'Tutorials' => 'This page lists all tutorials. Add your lessons here.',
        'Projects' => 'This page displays projects. Add sample student projects here.',
        'Equivalence' => 'This page explains equivalence and related academic details.'
    ];

    $created_page_ids = [];

    foreach ($pages as $title => $content) {
        $page_check = get_page_by_title($title);
        if (!isset($page_check->ID)) {
            $page_id = wp_insert_post([
                'post_title'   => $title,
                'post_content' => $content,
                'post_status'  => 'publish',
                'post_type'    => 'page'
            ]);
            $created_page_ids[] = $page_id;
        } else {
            $created_page_ids[] = $page_check->ID;
        }
    }

    // Create menu
    $menu_name = 'Top Menu Auto';
    $menu_exists = wp_get_nav_menu_object($menu_name);

    if (!$menu_exists) {
        $menu_id = wp_create_nav_menu($menu_name);
        foreach ($created_page_ids as $pid) {
            wp_update_nav_menu_item($menu_id, 0, [
                'menu-item-title'  => get_the_title($pid),
                'menu-item-object' => 'page',
                'menu-item-object-id' => $pid,
                'menu-item-type'   => 'post_type',
                'menu-item-status' => 'publish'
            ]);
        }

        // Assign menu to "primary" location
        $locations = get_theme_mod('nav_menu_locations');
        $locations['primary'] = $menu_id;
        set_theme_mod('nav_menu_locations', $locations);
    }
}
register_activation_hook(__FILE__, 'amp_create_pages');

// Apply dark radiant background
function amp_dark_background_styles() {
    echo "
    <style>
        body {
            background: radial-gradient(circle at top, #1a1a1a, #000000);
            color: #e6e6e6;
            font-size: 18px;
            line-height: 1.6;
        }
        .entry-content, .page-content, article {
            background: rgba(255, 255, 255, 0.05);
            padding: 20px;
            border-radius: 10px;
            backdrop-filter: blur(4px);
        }
        a { color: #66ccff; }
        a:hover { color: #33aaff; }
    </style>
    ";
}
add_action('wp_head', 'amp_dark_background_styles');


How It Works

✔ Creates pages automatically

Each page receives simple sample content.

✔ Creates a top navigation menu

Menu is assigned to theme’s Primary location.

✔ Adds a lucid dark radiant background

Dark smooth gradient
Subtle glass-blur box for page content
Contrast text for readability


💡 How to Install

  1. Create folder:
    wp-content/plugins/auto-menu-pages/

  2. Create file:
    auto-menu-pages.php

  3. Paste code

  4. Go to WordPress Admin → Plugins

  5. Activate Auto Menu & Sample Pages



Friday, December 5, 2025

#15 Table with CRUD actions

Below is a simple, single-file WordPress plugin that:

✔ Creates database table cdat_students on activation
✔ Displays records in admin menu
✔ Provides CRUD operations (Create, Update, Delete)
✔ Uses dashicons for action icons
✔ Uses standard WordPress sanitization + nonce protection


Complete Single-File Plugin: cdat-students.php

<?php
/**
 * Plugin Name: CDAT Students Table Creator
 * Description: Creates cdat_students table on activation and displays records with shortcode [show_cdat_students].
 * Version: 1.0
 * Author: RMC  
 */

if (!defined('ABSPATH')) exit;

/*===========================================
  CREATE TABLE ON PLUGIN ACTIVATION
===========================================*/
function cdat_students_create_table() {
    global $wpdb;
    $table = $wpdb->prefix . 'cdat_students';
    $charset = $wpdb->get_charset_collate();

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $sql = "CREATE TABLE $table (
        id INT(11) NOT NULL AUTO_INCREMENT,
        roll VARCHAR(20) NOT NULL,
        name VARCHAR(200) NOT NULL,
        semester INT(2) NOT NULL,
        PRIMARY KEY (id)
    ) $charset;";

    dbDelta($sql);

    // Insert sample data only if table empty
    $count = $wpdb->get_var("SELECT COUNT(*) FROM $table");
    if ($count == 0) {
        $wpdb->insert($table, array('roll' => '101', 'name' => 'John Doe', 'semester' => 1));
        $wpdb->insert($table, array('roll' => '102', 'name' => 'Arun Kumar', 'semester' => 1));
        $wpdb->insert($table, array('roll' => '103', 'name' => 'Priya Sharma', 'semester' => 2));
        $wpdb->insert($table, array('roll' => '104', 'name' => 'Maria L', 'semester' => 2));
    }
}
register_activation_hook(__FILE__, 'cdat_students_create_table');


/*===========================================
  SHORTCODE TO DISPLAY STUDENT TABLE
===========================================*/
function cdat_students_display_shortcode() {
    global $wpdb;
    $table = $wpdb->prefix . 'cdat_students';

    $rows = $wpdb->get_results("SELECT * FROM $table ORDER BY semester, roll", ARRAY_A);

    if (empty($rows)) {
        return "<p>No student records found.</p>";
    }

    $html = "<h3>CDAT Students</h3>";
    $html .= "<table style='width:100%; border-collapse:collapse;'>";

    // Header
    $html .= "<tr>
                <th style='border:1px solid #ccc; padding:6px;'>ID</th>
                <th style='border:1px solid #ccc; padding:6px;'>Roll</th>
                <th style='border:1px solid #ccc; padding:6px;'>Name</th>
                <th style='border:1px solid #ccc; padding:6px;'>Semester</th>
             </tr>";

    // Rows
    foreach ($rows as $r) {
        $html .= "<tr>
                    <td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['id'])."</td>
                    <td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['roll'])."</td>
                    <td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['name'])."</td>
                    <td style='border:1px solid #ccc; padding:6px;'>".esc_html($r['semester'])."</td>
                  </tr>";
    }

    $html .= "</table>";

    return $html;
}
add_shortcode('show_cdat_students', 'cdat_students_display_shortcode');


✔ Features Included

✔ Table auto-creation

✔ Admin menu

✔ List, Add, Edit, Delete

✔ Icons (dashicons-edit, dashicons-trash)

✔ SQL injection safe

✔ WordPress nonce security

✔ Single file, ready to use

#14 Table creation

 Below is a **complete WordPress plugin** that automatically **creates a sample table `wp_cdat_students` on activation**.

The plugin:

✅ Creates table `wp_cdat_students`

✅ Adds sample columns (id, roll, name, semester)

✅ Inserts **sample records**

✅ Includes shortcode `[show_cdat_students]` to display the table

✅ Safe + production-ready

---

# ✅ **Complete WordPress Plugin Code**

Create file:

**`wp-content/plugins/cdat-students/cdat-students.php`**

Paste the full code below:

<?php
/**
 * Plugin Name: CDAT Students CRUD
 * Description: Simple CRUD interface for cdat_students table.
 * Version: 1.0
 * Author: Civil Dept
 */

// -----------------------------------------------------------------------------
// 1. CREATE TABLE ON ACTIVATION
// -----------------------------------------------------------------------------
register_activation_hook(__FILE__, 'cdat_create_students_table');
function cdat_create_students_table() {
    global $wpdb;
    $table = $wpdb->prefix . "cdat_students";

    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table (
        id INT(11) NOT NULL AUTO_INCREMENT,
        name VARCHAR(200) NOT NULL,
        regno VARCHAR(50) NOT NULL,
        semester INT(11) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY(id)
    ) $charset;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// -----------------------------------------------------------------------------
// 2. ADMIN MENU
// -----------------------------------------------------------------------------
add_action('admin_menu', 'cdat_students_menu');
function cdat_students_menu() {
    add_menu_page(
        "Students", "Students", "manage_options",
        "cdat-students", "cdat_students_page",
        "dashicons-welcome-learn-more", 34
    );
}

// -----------------------------------------------------------------------------
// 3. MAIN PAGE LOGIC (CRUD)
// -----------------------------------------------------------------------------
function cdat_students_page() {
    global $wpdb;
    $table = $wpdb->prefix . "cdat_students";

    echo "<h1>CDAT Students</h1>";

    // ------------------------
    // DELETE ACTION
    // ------------------------
    if (isset($_GET['action']) && $_GET['action'] == "delete" && isset($_GET['id'])) {
        $id = intval($_GET['id']);

        if (!wp_verify_nonce($_GET['_wpnonce'], "cdat_delete_$id")) {
            die("Security check failed");
        }

        $wpdb->delete($table, ['id' => $id]);
        echo "<div class='updated'><p>Deleted Successfully</p></div>";
    }

    // ------------------------
    // SAVE NEW / EDIT
    // ------------------------
    if (isset($_POST['cdat_save_student'])) {
        $data = [
            "name"     => sanitize_text_field($_POST['name']),
            "regno"    => sanitize_text_field($_POST['regno']),
            "semester" => intval($_POST['semester']),
        ];

        if ($_POST['id'] == 0) {
            $wpdb->insert($table, $data);
            echo "<div class='updated'><p>Student Added.</p></div>";
        } else {
            $wpdb->update($table, $data, ['id' => intval($_POST['id'])]);
            echo "<div class='updated'><p>Student Updated.</p></div>";
        }
    }

    // ------------------------
    // EDIT FORM
    // ------------------------
    $edit = null;

    if (isset($_GET['action']) && $_GET['action'] == "edit" && isset($_GET['id'])) {
        $id = intval($_GET['id']);
        $edit = $wpdb->get_row("SELECT * FROM $table WHERE id=$id");
    }

    ?>

    <h2><?php echo $edit ? "Edit Student" : "Add Student"; ?></h2>

    <form method="post">
        <input type="hidden" name="id" value="<?php echo $edit ? $edit->id : 0; ?>">

        <table class="form-table">
            <tr>
                <th>Name:</th>
                <td><input type="text" name="name" required value="<?php echo $edit ? esc_attr($edit->name) : ""; ?>"></td>
            </tr>
            <tr>
                <th>Reg No:</th>
                <td><input type="text" name="regno" required value="<?php echo $edit ? esc_attr($edit->regno) : ""; ?>"></td>
            </tr>
            <tr>
                <th>Semester:</th>
                <td><input type="number" name="semester" min="1" max="8" required value="<?php echo $edit ? esc_attr($edit->semester) : ""; ?>"></td>
            </tr>
        </table>

        <button class="button button-primary" type="submit" name="cdat_save_student">
            <?php echo $edit ? "Update" : "Add"; ?>
        </button>
    </form>

    <hr>

    <h2>All Students</h2>

    <?php
        $rows = $wpdb->get_results("SELECT * FROM $table ORDER BY id DESC");

        if (!$rows) {
            echo "<p>No students found.</p>";
            return;
        }
    ?>

    <table class="wp-list-table widefat striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Reg No</th>
                <th>Semester</th>
                <th>Actions</th>
            </tr>
        </thead>

        <tbody>
        <?php foreach ($rows as $r): ?>
            <tr>
                <td><?php echo $r->id; ?></td>
                <td><?php echo esc_html($r->name); ?></td>
                <td><?php echo esc_html($r->roll); ?></td>
                <td><?php echo $r->semester; ?></td>
                <td>
                    <a href="?page=cdat-students&action=edit&id=<?php echo $r->id; ?>" title="Edit">
                        <span class="dashicons dashicons-edit"></span>
                    </a>

                    &nbsp;

                    <a href="<?php echo wp_nonce_url("?page=cdat-students&action=delete&id=$r->id", "cdat_delete_$r->id"); ?>"
                       onclick="return confirm('Delete this record?')" title="Delete">
                        <span class="dashicons dashicons-trash"></span>
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <?php
}
?>

# ✅ **How to Use**

### 1. Install Plugin

Create folder:

`wp-content/plugins/cdat-students/`

Put the file `cdat-students.php` inside it.

Activate the plugin.

---

# 2. Table Automatically Created

The plugin creates:

```

wp_cdat_students

```

With columns:

| id | roll | name | semester |

| -- | ---- | ---- | -------- |

And inserts sample records.

---

# 3. Display Student Table

Add this shortcode to any page:

```

[show_cdat_students]

```

✔ Shows all students

✔ Styled HTML table

---


Wednesday, November 12, 2025

Welcome to RMC online Tutorials

WordPress Plugin Development – Full Course Index

WordPress Plugin Development
12-Module Learning Portal

#12 🧩 Module 12 – Plugin Security, Performance & Best Practices

Module 12 – Plugin Security, Performance & Best Practices

🧩 Module 12 – Plugin Security, Performance & Best Practices

In this final module, you’ll learn how to keep your WordPress plugin secure, fast, and reliable. We’ll cover sanitization, escaping, nonces, database safety, and performance tips.


Step 1 – Sanitize User Input

Always clean any data from users before saving to the database or displaying on screen.

$user_input = $_POST['username'] ?? ''; $clean_input = sanitize_text_field( $user_input ); // Example: Save safely update_option( 'mfp_username', $clean_input );

Step 2 – Escape Output

When printing values on a page, escape them to prevent XSS (Cross-Site Scripting).

$name = get_option('mfp_username'); echo '<h3>Hello, ' . esc_html( $name ) . '!</h3>';

Step 3 – Use Nonces for Form Security

Nonces ensure only valid requests modify data.

<form method="post"> <?php wp_nonce_field( 'mfp_save_data', 'mfp_nonce' ); ?> <input type="text" name="username"> <input type="submit" value="Save"> </form> <?php if ( isset($_POST['mfp_nonce']) && wp_verify_nonce($_POST['mfp_nonce'], 'mfp_save_data') ) { $username = sanitize_text_field($_POST['username']); update_option('mfp_username', $username); echo '<p style="color:#00ffa3">Saved!</p>'; } ?>

Step 4 – Use Prepared Statements for SQL

Avoid building SQL queries with string concatenation — use the $wpdb->prepare() method.

global $wpdb; $username = 'admin'; $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->users} WHERE user_login = %s", $username ) );

Step 5 – Performance Tips

  • ✅ Use transients to cache data from APIs or heavy DB queries.
  • ✅ Load scripts only when necessary using admin_enqueue_scripts conditions.
  • ✅ Use filemtime() for cache-busting only when scripts truly change.
  • ✅ Avoid loading large CSS/JS on pages where your plugin isn’t used.
// Example: conditional script load function myplugin_enqueue_scripts($hook) { if ( $hook !== 'toplevel_page_myplugin' ) return; wp_enqueue_script( 'myplugin-admin', plugin_dir_url(__FILE__) . 'admin.js', array('jquery'), filemtime(__FILE__), true ); } add_action('admin_enqueue_scripts', 'myplugin_enqueue_scripts');

Step 6 – Follow Coding Standards

  • Use snake_case for functions and variables.
  • Prefix everything (e.g., mfp_) to avoid name collisions.
  • Document your code with clear comments.
  • Validate your plugin with the WordPress Plugin Check tool.

Step 7 – Prepare for Distribution

  • Add readme.txt with description, version, author, and license.
  • Use proper folder structure (includes/, assets/, etc.).
  • Provide translation support with load_plugin_textdomain().
  • Keep plugin lightweight – load only what’s needed.

🎯 Wrap-Up

Congratulations! You’ve now built a full-featured WordPress plugin suite — from login systems, AJAX, REST API, Gutenberg blocks, widgets, to now secure and performant production-ready plugins.

✔ Next Steps: publish your plugin to WordPress.org or your own GitHub repository!

#11 Module 11 – Custom Widgets & Sidebars Integration next, using the same glowing interactive format

Module 11 – Custom Widgets & Sidebars Integration

🧩 Module 11 – Custom Widgets & Sidebars Integration

In this module, we’ll create a custom widget that displays a personalized message, and we’ll register a new sidebar where this widget can be placed.


Step 1 — Create the Plugin File

Create a new folder: my-custom-widget Then inside, create my-custom-widget.php:

<?php /** * Plugin Name: My Custom Widget * Description: Adds a simple custom widget and a sidebar to WordPress. * Version: 1.0 * Author: Your Name */ if ( ! defined( 'ABSPATH' ) ) exit; class My_Custom_Widget extends WP_Widget { function __construct() { parent::__construct( 'my_custom_widget', __( 'My Custom Widget', 'text_domain' ), array( 'description' => __( 'Displays a custom message', 'text_domain' ) ) ); } // Widget front-end display public function widget( $args, $instance ) { echo $args['before_widget']; echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title']; echo '<p style="color:#00ffa3;">' . esc_html( $instance['message'] ) . '</p>'; echo $args['after_widget']; } // Widget backend form public function form( $instance ) { $title = !empty( $instance['title'] ) ? $instance['title'] : __( 'My Widget', 'text_domain' ); $message = !empty( $instance['message'] ) ? $instance['message'] : __( 'Hello, World!', 'text_domain' ); ?> <p> <label>Title:</label> <input class="widefat" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <p> <label>Message:</label> <input class="widefat" name="<?php echo $this->get_field_name('message'); ?>" type="text" value="<?php echo esc_attr( $message ); ?>" /> </p> <?php } // Save widget form values public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = sanitize_text_field( $new_instance['title'] ); $instance['message'] = sanitize_text_field( $new_instance['message'] ); return $instance; } } // Register the widget function register_my_custom_widget() { register_widget( 'My_Custom_Widget' ); } add_action( 'widgets_init', 'register_my_custom_widget' ); // Register a custom sidebar function my_custom_sidebar() { register_sidebar( array( 'name' => __( 'Custom Sidebar', 'text_domain' ), 'id' => 'custom_sidebar', 'before_widget' => '<div class="widget-container">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'my_custom_sidebar' ); ?>

Step 2 — Activate and Test

  1. Place the folder my-custom-widget inside wp-content/plugins/.
  2. Go to Plugins → Activate "My Custom Widget".
  3. Go to Appearance → Widgets (or the block-based widget editor in newer WP).
  4. Find “My Custom Widget” and drag it into “Custom Sidebar.”
  5. Set your custom title and message, then save.
  6. To display sidebar in your theme, add this to sidebar.php or similar:
<?php if ( is_active_sidebar( 'custom_sidebar' ) ) : ?> <aside id="secondary"> <?php dynamic_sidebar( 'custom_sidebar' ); ?> </aside> <?php endif; ?>

✅ Output

When placed in the sidebar, your widget will show:

  • Widget Title (editable from admin)
  • Custom message (editable)
  • Styled automatically by your theme

💡 Notes

  • Widgets are great for dynamic content areas (sidebars, footers, etc.).
  • You can register multiple widgets using the same structure.
  • Widgets can include forms, data from APIs, or even shortcodes.

17 Auto pages Manu

 Prompt: can you create plugin to add menu at top for pages like login, contactus, tutorials, projects, equivalence. Create the above pages ...