Category: WordPress

Creating a custom mobile OTP (One-Time Password) system in a WordPress contact form

Creating a custom mobile OTP (One-Time Password) system in a WordPress contact form requires the following steps:


Steps to Implement Mobile OTP in WordPress Contact Form

  1. Create a Contact Form
    • Add fields like name, mobile number, and OTP.
  2. Generate and Send OTP to Mobile
    • Use a third-party SMS gateway like Twilio, Nexmo (Vonage), or Textlocal to send OTPs to mobile numbers.
  3. Store the OTP Temporarily
    • Save the OTP in a session or database with a timestamp for validation.
  4. Verify OTP
    • Add a second step in the form where users enter the OTP for verification.
  5. Proceed After Verification
    • Submit the form only if the OTP is verified successfully.

Code Implementation

Step 1: Add Form HTML

Create a custom form with fields for mobile and OTP:

<form id="custom-mobile-otp-form" method="post" action="">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    
    <label for="mobile">Mobile Number:</label>
    <input type="text" id="mobile" name="mobile" required>
    <button type="button" id="send-otp">Send OTP</button>

    <div id="otp-section" style="display:none;">
        <label for="otp">Enter OTP:</label>
        <input type="text" id="otp" name="otp" required>
        <button type="submit" id="verify-otp">Submit</button>
    </div>
</form>
<div id="response-message"></div>

Step 2: Handle OTP via AJAX

Generate and Send OTP

Add this PHP code to your theme’s functions.php file:

add_action('wp_ajax_send_mobile_otp', 'handle_send_mobile_otp');
add_action('wp_ajax_nopriv_send_mobile_otp', 'handle_send_mobile_otp');

function handle_send_mobile_otp() {
    session_start();
    $mobile = sanitize_text_field($_POST['mobile']);
    $otp = rand(100000, 999999); // Generate a 6-digit OTP
    $_SESSION['mobile_otp'] = $otp;
    $_SESSION['mobile_otp_expiry'] = time() + 300; // OTP valid for 5 minutes

    // Integrate SMS Gateway API (e.g., Twilio, Nexmo, Textlocal)
    $api_key = 'YOUR_API_KEY'; // Replace with your SMS gateway API key
    $sender = 'TXTLCL';        // Replace with your SMS sender ID
    $message = "Your OTP is $otp. It is valid for 5 minutes.";

    // Example API Request for Textlocal
    $url = "https://api.textlocal.in/send/?apikey=$api_key&numbers=$mobile&message=" . urlencode($message) . "&sender=$sender";
    $response = wp_remote_get($url);

    if (is_wp_error($response)) {
        wp_send_json_error('Failed to send OTP. Please try again.');
    }

    wp_send_json_success('OTP sent successfully to ' . $mobile . '!');
}
Verify OTP

Add the following code to verify the OTP:

add_action('wp_ajax_verify_mobile_otp', 'handle_verify_mobile_otp');
add_action('wp_ajax_nopriv_verify_mobile_otp', 'handle_verify_mobile_otp');

function handle_verify_mobile_otp() {
    session_start();
    $user_otp = sanitize_text_field($_POST['otp']);

    if (isset($_SESSION['mobile_otp']) && isset($_SESSION['mobile_otp_expiry'])) {
        if (time() > $_SESSION['mobile_otp_expiry']) {
            wp_send_json_error('OTP expired!');
        } elseif ($user_otp == $_SESSION['mobile_otp']) {
            unset($_SESSION['mobile_otp']);
            unset($_SESSION['mobile_otp_expiry']);
            wp_send_json_success('OTP verified! Form submitted successfully.');
        } else {
            wp_send_json_error('Invalid OTP!');
        }
    } else {
        wp_send_json_error('No OTP found!');
    }
}

Step 3: Add JavaScript for AJAX

Create a custom JavaScript file and enqueue it in your theme:

jQuery(document).ready(function ($) {
    $('#send-otp').click(function () {
        const mobile = $('#mobile').val();

        if (mobile) {
            $.ajax({
                url: ajaxurl, // WordPress AJAX URL
                method: 'POST',
                data: {
                    action: 'send_mobile_otp',
                    mobile: mobile,
                },
                success: function (response) {
                    if (response.success) {
                        alert(response.data);
                        $('#otp-section').show();
                    } else {
                        alert(response.data);
                    }
                },
            });
        } else {
            alert('Please enter your mobile number.');
        }
    });

    $('#custom-mobile-otp-form').submit(function (e) {
        e.preventDefault();
        const otp = $('#otp').val();

        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'verify_mobile_otp',
                otp: otp,
            },
            success: function (response) {
                if (response.success) {
                    $('#response-message').text(response.data);
                } else {
                    $('#response-message').text(response.data);
                }
            },
        });
    });
});

Enqueue this script in your theme’s functions.php file:

function custom_enqueue_mobile_otp_scripts() {
    wp_enqueue_script('custom-mobile-otp', get_template_directory_uri() . '/js/custom-mobile-otp.js', ['jquery'], null, true);
    wp_localize_script('custom-mobile-otp', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'custom_enqueue_mobile_otp_scripts');

Step 4: Test the Implementation

  1. Add the form to a WordPress page or template.
  2. Test sending and verifying the OTP via the mobile number.

Notes

  • Replace the placeholder API details with those from your SMS gateway provider.
  • Use HTTPS and secure your SMS API key.
  • Optionally, save form submissions in the WordPress database after OTP verification for future reference.

Creating a custom email OTP (One-Time Password) system in a WordPress contact form

Creating a custom email OTP (One-Time Password) system in a WordPress contact form involves these steps:

Steps to Implement Email OTP in WordPress Contact Form

  1. Create a Custom Contact Form
    • You can create a custom contact form using a plugin like Contact Form 7, WPForms, or create one manually using custom code.
  2. Send OTP to User’s Email
    • When a user fills out the form and submits, generate a random OTP and send it to the email provided.
  3. Store the OTP Temporarily
    • Save the OTP in a session or database with a timestamp to allow verification within a specific time.
  4. Verify the OTP
    • Provide a second step in the form where the user can enter the OTP for verification.
  5. Proceed After Verification
    • If the OTP matches and is within the valid time, allow the user to proceed with the contact form submission.

Code Example for Custom Implementation

Here is an example of how to do this using custom code in a WordPress theme or plugin:

Step 1: Enqueue Scripts

Add the following in your theme’s functions.php file to load necessary scripts:

function custom_enqueue_scripts() {
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

Step 2: Create the Form

Add the following form to a page or template:

<form id="custom-contact-form" method="post" action="">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <button type="button" id="send-otp">Send OTP</button>

    <div id="otp-section" style="display:none;">
        <label for="otp">Enter OTP:</label>
        <input type="text" id="otp" name="otp" required>
        <button type="submit" id="verify-otp">Submit</button>
    </div>
</form>
<div id="response-message"></div>

Step 3: Handle OTP via AJAX

Add this PHP code to handle OTP generation and verification:

add_action('wp_ajax_send_otp', 'handle_send_otp');
add_action('wp_ajax_nopriv_send_otp', 'handle_send_otp');

function handle_send_otp() {
    session_start();
    $email = sanitize_email($_POST['email']);
    $otp = rand(100000, 999999); // Generate a 6-digit OTP
    $_SESSION['otp'] = $otp;
    $_SESSION['otp_expiry'] = time() + 300; // OTP valid for 5 minutes

    // Send the OTP via email
    $subject = "Your OTP Code";
    $message = "Your OTP is: $otp";
    $headers = ['Content-Type: text/html; charset=UTF-8'];
    wp_mail($email, $subject, $message, $headers);

    wp_send_json_success('OTP sent successfully!');
}

add_action('wp_ajax_verify_otp', 'handle_verify_otp');
add_action('wp_ajax_nopriv_verify_otp', 'handle_verify_otp');

function handle_verify_otp() {
    session_start();
    $user_otp = sanitize_text_field($_POST['otp']);

    if (isset($_SESSION['otp']) && isset($_SESSION['otp_expiry'])) {
        if (time() > $_SESSION['otp_expiry']) {
            wp_send_json_error('OTP expired!');
        } elseif ($user_otp == $_SESSION['otp']) {
            unset($_SESSION['otp']);
            unset($_SESSION['otp_expiry']);
            wp_send_json_success('OTP verified!');
        } else {
            wp_send_json_error('Invalid OTP!');
        }
    } else {
        wp_send_json_error('No OTP found!');
    }
}

Step 4: Add AJAX in JavaScript

Create a custom JavaScript file, enqueue it, and add the following:

jQuery(document).ready(function ($) {
    $('#send-otp').click(function () {
        const email = $('#email').val();

        if (email) {
            $.ajax({
                url: ajaxurl, // WordPress AJAX URL
                method: 'POST',
                data: {
                    action: 'send_otp',
                    email: email,
                },
                success: function (response) {
                    if (response.success) {
                        alert(response.data);
                        $('#otp-section').show();
                    } else {
                        alert('Failed to send OTP. Please try again.');
                    }
                },
            });
        } else {
            alert('Please enter your email.');
        }
    });

    $('#custom-contact-form').submit(function (e) {
        e.preventDefault();
        const otp = $('#otp').val();

        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'verify_otp',
                otp: otp,
            },
            success: function (response) {
                if (response.success) {
                    $('#response-message').text('Form submitted successfully!');
                } else {
                    $('#response-message').text(response.data);
                }
            },
        });
    });
});

Step 5: Test the Form

  • Add the form to a WordPress page.
  • Test sending and verifying the OTP.

Notes

  • For session handling, ensure your hosting supports PHP sessions.
  • You can enhance security by storing the OTP in a database instead of PHP sessions.
  • Consider using reCAPTCHA or another spam protection mechanism.

Custom hooks in WordPress across plugins

Custom hooks in WordPress are a powerful way to allow plugins or themes to interact and extend functionality without directly modifying code. You can create custom hooks (actions or filters) in one plugin and then use those hooks in another plugin to modify behavior or extend functionality.Here’s a step-by-step guide to creating and using custom hooks across plugins:

Step 1: Define a Custom Hook

Custom hooks can be either actions or filters. Define them in the plugin where you want the hook to be available.

Example: Define a Custom Action Hook

In your first plugin (plugin-a.php):

<?php
// Plugin A: Define a custom action hook
function plugin_a_custom_action() {
    do_action('plugin_a_custom_action');
}
add_action('init', 'plugin_a_custom_action');

Example: Define a Custom Filter Hook

In your first plugin (plugin-a.php):

<?php
// Plugin A: Define a custom filter hook
function plugin_a_modify_content($content) {
    $content = apply_filters('plugin_a_filter_content', $content);
    return $content;
}
add_filter('the_content', 'plugin_a_modify_content');

Step 2: Use the Custom Hook in Another Plugin

In the second plugin (plugin-b.php), you can hook into the custom action or filter defined in Plugin A.

Example: Use a Custom Action HookStep 2: Use the Custom Hook in Another Plugin

In the second plugin (plugin-b.php), you can hook into the custom action or filter defined in Plugin A.

Example: Use a Custom Action Hook

<?php
// Plugin B: Add functionality to the custom action hook
function plugin_b_add_to_action() {
    echo '<p>This is added by Plugin B using Plugin A\'s custom action.</p>';
}
add_action('plugin_a_custom_action', 'plugin_b_add_to_action');

Example: Use a Custom Filter Hook

<?php
// Plugin B: Modify the content using the custom filter hook
function plugin_b_modify_content($content) {
    return $content . '<p>Additional content added by Plugin B.</p>';
}
add_filter('plugin_a_filter_content', 'plugin_b_modify_content');

Step 3: Pass Data to the Hook

Custom hooks can pass data that other plugins can use.

Example: Custom Action Hook with Parameters

In Plugin A:

<?php
// Define an action hook with parameters
function plugin_a_custom_action_with_data() {
    $data = 'Hello from Plugin A!';
    do_action('plugin_a_custom_action_with_data', $data);
}
add_action('init', 'plugin_a_custom_action_with_data');

In Plugin B:

<?php
// Hook into the action and use the passed data
function plugin_b_receive_data($data) {
    echo '<p>Plugin B received: ' . esc_html($data) . '</p>';
}
add_action('plugin_a_custom_action_with_data', 'plugin_b_receive_data');

Step 4: Use Hook Priorities

Hooks in WordPress support priorities, allowing you to control the order in which multiple functions run.

Example:

<?php
// Plugin B: Add content with a higher priority (runs first)
function plugin_b_high_priority($content) {
    return '<p>High Priority Content from Plugin B.</p>' . $content;
}
add_filter('plugin_a_filter_content', 'plugin_b_high_priority', 5);

// Plugin B: Add content with a lower priority (runs later)
function plugin_b_low_priority($content) {
    return $content . '<p>Low Priority Content from Plugin B.</p>';
}
add_filter('plugin_a_filter_content', 'plugin_b_low_priority', 15);

Step 5: Debug Custom Hooks

  1. Check if a Hook Exists
    Use has_action() or has_filter() to verify if a hook is being used:
if (has_action('plugin_a_custom_action')) {
    echo 'Action hook is available!';
}

View All Hooked Functions
Use current_filter() inside a hooked function to debug the current hook.

Logging Hook Execution
Use error_log() or wp_debug() to log hook execution.

Real-Life Use Case: Sending Custom Data Across Plugins

Plugin A: Define Hook for Sending Data

<?php
// Plugin A: Custom action hook for sending order data
function plugin_a_order_completed($order_id, $order_data) {
    do_action('plugin_a_order_completed', $order_id, $order_data);
}

Plugin B: Hook into Order Completion

<?php
// Plugin B: Use data passed from Plugin A
function plugin_b_handle_order($order_id, $order_data) {
    error_log('Order ID: ' . $order_id);
    error_log('Order Data: ' . print_r($order_data, true));
}
add_action('plugin_a_order_completed', 'plugin_b_handle_order', 10, 2);

Best Practices for Custom Hooks

  1. Prefix Hook Names: Use unique prefixes to avoid naming conflicts. For example: plugin_a_custom_action.
  2. Documentation: Document the hook usage in your plugin to guide other developers.
  3. Test Across Plugins: Ensure the hooks work when both plugins are active.
  4. Performance: Avoid overusing hooks to minimize performance overhead.

Let me know if you need help implementing this in your specific use case!

How to Add a Shortcode in WordPress

Adding a shortcode in WordPress is a straightforward process. Shortcodes allow you to add custom functionality or display specific content by inserting a simple code snippet in posts, pages, or widgets. Here’s how to create and use a shortcode in WordPress:


Step 1: Create a Shortcode

To create a shortcode, use the add_shortcode() function in your theme’s functions.php file or a custom plugin.

Example: A Simple Shortcode This shortcode will display a custom message.

// Create a shortcode to display a message
function my_custom_shortcode() {
    return '<p>This is my custom shortcode!</p>';
}
add_shortcode('my_shortcode', 'my_custom_shortcode');

Usage: Insert [my_shortcode] into any post, page, or widget, and it will display:

This is my custom shortcode!

Step 2: Add Parameters to the Shortcode

You can make the shortcode more dynamic by adding attributes.

Example: Shortcode with Parameters

// Create a shortcode with attributes
function my_dynamic_shortcode($atts) {
    // Set default attributes
    $atts = shortcode_atts(
        array(
            'name' => 'Guest',
        ),
        $atts,
        'dynamic_shortcode'
    );

    return '<p>Hello, ' . esc_html($atts['name']) . '!</p>';
}
add_shortcode('dynamic_shortcode', 'my_dynamic_shortcode');

Usage:

  • [dynamic_shortcode name="John"] will display:

Hello, John!

[dynamic_shortcode] will display: Hello, Guest!

Step 3: Add Content Inside the Shortcode

Some shortcodes allow users to wrap content within them.

Example: Shortcode with Enclosed Content

// Create a shortcode that accepts content
function my_content_shortcode($atts, $content = null) {
    return '<div class="custom-box">' . do_shortcode($content) . '</div>';
}
add_shortcode('content_shortcode', 'my_content_shortcode');

Usage: Insert [content_shortcode]Your custom content here[/content_shortcode].

Output:

Your custom content here

Step 4: Use the Shortcode in Posts, Pages, or Widgets

  1. Insert the shortcode directly in the WordPress editor:

2. Use shortcodes in PHP files:

echo do_shortcode('[my_shortcode]');

Step 5: Use Shortcodes in Widgets

To use shortcodes in text widgets or custom HTML widgets, ensure shortcodes are enabled for widgets:

Enable Shortcodes in Widgets: Add this to your functions.php file:

add_filter('widget_text', 'do_shortcode');

Advanced Shortcode Examples

Example 1: Display Recent Posts

Usage: Insert [recent_posts count="3"] to display 3 recent posts.

Example 2: Display User Info

function user_info_shortcode() {
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        return '<p>Welcome, ' . esc_html($current_user->display_name) . '!</p>';
    } else {
        return '<p>Please <a href="' . wp_login_url() . '">log in</a>.</p>';
    }
}
add_shortcode('user_info', 'user_info_shortcode');

Usage: Insert [user_info] to display user-specific information.

Tips for Writing Shortcodes

  1. Escape Output: Always sanitize user input and escape output to avoid security vulnerabilities.
    • Use esc_html() for text output.
    • Use esc_url() for links.
  2. Use Default Attributes: Use shortcode_atts() to define default attribute values.
  3. Test Thoroughly: Ensure your shortcode works across themes and WordPress versions.

Let me know if you’d like help building a specific shortcode!

Create register form without a plugin

Creating a custom registration form in WordPress without using a plugin involves a few steps. This includes creating the form, handling form submission, and storing user data in the WordPress database. Here’s a step-by-step guide:


Step 1: Create a Registration Form

You can create a simple form using HTML and include it in your theme file (e.g., page-register.php) or use a shortcode.

HTML Form Code:

<?php
function custom_registration_form() {
    ob_start(); ?>
    <form method="post" action="">
        <p>
            <label for="username">Username</label>
            <input type="text" name="username" id="username" required>
        </p>
        <p>
            <label for="email">Email</label>
            <input type="email" name="email" id="email" required>
        </p>
        <p>
            <label for="password">Password</label>
            <input type="password" name="password" id="password" required>
        </p>
        <p>
            <input type="submit" name="submit" value="Register">
        </p>
    </form>
    <?php
    return ob_get_clean();
}
add_shortcode('custom_registration_form', 'custom_registration_form');

You can now use the [custom_registration_form] shortcode to display the form on any page or post.


Step 2: Handle Form Submission

Process the form submission, validate inputs, and register the user in WordPress.

Code:

function custom_registration_form_handler() {
    if (isset($_POST['submit'])) {
        $username = sanitize_user($_POST['username']);
        $email = sanitize_email($_POST['email']);
        $password = sanitize_text_field($_POST['password']);

        // Check if username or email already exists
        if (username_exists($username)) {
            echo '<p style="color: red;">Username already exists!</p>';
            return;
        }
        if (email_exists($email)) {
            echo '<p style="color: red;">Email already exists!</p>';
            return;
        }

        // Register the user
        $user_id = wp_create_user($username, $password, $email);
        if (is_wp_error($user_id)) {
            echo '<p style="color: red;">An error occurred: ' . $user_id->get_error_message() . '</p>';
        } else {
            echo '<p style="color: green;">Registration successful! You can now log in.</p>';
        }
    }
}
add_action('init', 'custom_registration_form_handler');

Step 3: Redirect After Registration (Optional)

If you want to redirect the user after successful registration, modify the handler:

Code:

if (!is_wp_error($user_id)) {
    wp_redirect(home_url('/login')); // Replace '/login' with your login page URL
    exit;
}

Step 4: Add Styles (Optional)

Add custom CSS to style your form.

CSS:

form {
    max-width: 400px;
    margin: 0 auto;
}
form p {
    margin-bottom: 15px;
}
form label {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
}
form input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
}
form input[type="submit"] {
    background-color: #0073aa;
    color: #fff;
    border: none;
    cursor: pointer;
}
form input[type="submit"]:hover {
    background-color: #005177;
}

Step 5: Display the Form

  1. Use the [custom_registration_form] shortcode on any page.
  2. Alternatively, include the form directly in a PHP file:
echo do_shortcode('[custom_registration_form]');

Step 6: Test the Form
  • Create a new page and insert the [custom_registration_form] shortcode.Visit the page and try registering a new user.Verify the user is added in the WordPress admin under Users.
  • Note
  • Security: Ensure that the form is secure by adding nonce fields and escaping outputs.

  • wp_nonce_field('custom_registration_form_action', 'custom_registration_form_nonce');
    

    Then validate it in the form handler:

    if (!isset($_POST['custom_registration_form_nonce']) || 
        !wp_verify_nonce($_POST['custom_registration_form_nonce'], 'custom_registration_form_action')) {
        echo '<p style="color: red;">Security check failed!</p>';
        return;
    }
    

    Custom Fields: If you want to add custom fields (e.g., phone number), include them in the form and save them as user meta:

    update_user_meta($user_id, 'phone', sanitize_text_field($_POST['phone']));
    

    This approach creates a lightweight and customizable registration form for WordPress. Let me know if you need further enhancements!

    PluginHow to Create WordPress Plugin from Scratch – WP

    Creating a WordPress plugin from scratch involves several steps. Here’s a complete guide to help you build your first plugin:


    Step 1: Setup the Plugin Folder and File

    1. Navigate to the wp-content/plugins directory of your WordPress installation.
    2. Create a new folder for your plugin. For example: my-first-plugin.
    3. Inside this folder, create a main PHP file. For example: my-first-plugin.php.

    Step 2: Add Plugin Header Information

    Add the following code to the top of your my-first-plugin.php file. This provides WordPress with details about your plugin.

    <?php
    /**
     * Plugin Name: My First Plugin
     * Plugin URI: https://example.com/
     * Description: A simple plugin to demonstrate WordPress plugin development.
     * Version: 1.0
     * Author: Your Name
     * Author URI: https://example.com/
     * License: GPL2
     */
    

    This is essential for WordPress to recognize your plugin.


    Step 3: Activate the Plugin

    1. Log in to your WordPress admin panel.
    2. Go to Plugins > Installed Plugins.
    3. Find “My First Plugin” in the list and click Activate.

    Step 4: Add Basic Functionality

    For demonstration, let’s add functionality to display a message at the end of every post.

    Code:

    // Add content at the end of the post
    function my_plugin_add_content($content) {
        if (is_single()) {
            $content .= '<p style="color: blue;">Thank you for reading this post! - My First Plugin</p>';
        }
        return $content;
    }
    add_filter('the_content', 'my_plugin_add_content');
    

    Step 5: Add a Shortcode

    Let’s create a shortcode [my_plugin_shortcode] to display a custom message anywhere.

    Code:

    // Create a shortcode
    function my_plugin_shortcode() {
        return '<p>This is a message from My First Plugin!</p>';
    }
    add_shortcode('my_plugin_shortcode', 'my_plugin_shortcode');
    

    Now, you can use [my_plugin_shortcode] in posts, pages, or widgets.


    Step 6: Create a Custom Admin Page

    Let’s add a settings page in the WordPress admin dashboard.

    Code:

    // Add a custom admin menu
    function my_plugin_add_admin_menu() {
        add_menu_page(
            'My First Plugin Settings', // Page title
            'My Plugin',               // Menu title
            'manage_options',          // Capability
            'my-plugin-settings',      // Menu slug
            'my_plugin_settings_page', // Callback function
            'dashicons-admin-generic', // Icon
            90                         // Position
        );
    }
    add_action('admin_menu', 'my_plugin_add_admin_menu');
    // Create the settings page
    function my_plugin_settings_page() {
        echo '<h1>My First Plugin Settings</h1>';
        echo '<p>Here you can manage settings for My First Plugin.</p>';
    }
    

    Step 7: Enqueue Styles and Scripts

    If your plugin requires custom CSS or JavaScript, enqueue them properly.

    Code:

    // Enqueue custom styles and scripts
    function my_plugin_enqueue_scripts() {
        wp_enqueue_style('my-plugin-style', plugin_dir_url(__FILE__) . 'css/style.css');
        wp_enqueue_script('my-plugin-script', plugin_dir_url(__FILE__) . 'js/script.js', array('jquery'), null, true);
    }
    add_action('wp_enqueue_scripts', 'my_plugin_enqueue_scripts');
    

    Step 8: Use Hooks and Filters

    WordPress provides hooks (actions and filters) to integrate custom functionality. Use them to extend WordPress features.

    For example, using the admin_notices action to display an admin notice:

    Code:

    // Display an admin notice
    function my_plugin_admin_notice() {
        echo '<div class="notice notice-success is-dismissible">
            <p>My First Plugin has been activated successfully!</p>
        </div>';
    }
    add_action('admin_notices', 'my_plugin_admin_notice');
    

    Step 9: Make It Translatable

    Add internationalization support so your plugin can be translated into other languages.

    Code:

    // Load plugin text domain
    function my_plugin_load_textdomain() {
        load_plugin_textdomain('my-first-plugin', false, dirname(plugin_basename(__FILE__)) . '/languages/');
    }
    add_action('plugins_loaded', 'my_plugin_load_textdomain');
    
    1. Create a languages folder.
    2. Use tools like Poedit to create .po and .mo translation files.

    Step 10: Test and Debug

    • Test in different themes: Ensure your plugin works with various WordPress themes.
    • Debug: Enable debugging in wp-config.php by setting WP_DEBUG to true.

    Folder Structure Example

    my-first-plugin/
    ├── css/
    │   └── style.css
    ├── js/
    │   └── script.js
    ├── languages/
    │   └── my-first-plugin-en_US.mo
    │   └── my-first-plugin-en_US.po
    └── my-first-plugin.php
    

    Final Steps

    • Follow WordPress coding standards.
    • Add proper comments to your code.
    • Test your plugin thoroughly.

    Congratulations! You’ve created a basic WordPress plugin from scratch. Let me know if you need help with specific features!

    how to add WooCommerce product add-ons without a plugin

    Adding product add-ons to WooCommerce without a plugin can be achieved using custom fields and hooks. Here’s a step-by-step guide:

    Scenario: Add a Custom Add-On Field (e.g., Gift Message)

    This guide demonstrates how to add a text field for customers to enter a “Gift Message” on the product page and save it with the order.


    Step 1: Add the Add-On Field to the Product Page

    Use the woocommerce_before_add_to_cart_button hook to display the add-on field on the single product page.

    Code: Add this to your theme’s functions.php file:

    // Add custom add-on field to product page
    add_action('woocommerce_before_add_to_cart_button', 'add_custom_product_addon_field');
    function add_custom_product_addon_field() {
        echo '<div class="custom-product-addon">';
        echo '<label for="gift_message">' . __('Gift Message', 'woocommerce') . '</label>';
        echo '<textarea id="gift_message" name="gift_message" rows="3" cols="20" placeholder="Enter your gift message"></textarea>';
        echo '</div>';
    }
    

    Step 2: Validate the Add-On Field

    Ensure the field is not empty (if required) before adding the product to the cart.

    Code:

    // Validate custom add-on field
    add_filter('woocommerce_add_to_cart_validation', 'validate_custom_product_addon_field', 10, 2);
    function validate_custom_product_addon_field($passed, $product_id) {
        if (isset($_POST['gift_message']) && empty($_POST['gift_message'])) {
            wc_add_notice(__('Please enter a gift message.', 'woocommerce'), 'error');
            return false;
        }
        return $passed;
    }
    

    Step 3: Save the Add-On Field to the Cart

    Save the add-on field value in the cart session.

    Code:

    // Save custom add-on field to cart item data
    add_filter('woocommerce_add_cart_item_data', 'save_custom_product_addon_field', 10, 2);
    function save_custom_product_addon_field($cart_item_data, $product_id) {
        if (isset($_POST['gift_message'])) {
            $cart_item_data['gift_message'] = sanitize_text_field($_POST['gift_message']);
            $cart_item_data['unique_key'] = md5(microtime()); // Prevent cart item merging
        }
        return $cart_item_data;
    }
    

    Step 4: Display the Add-On Field in the Cart and Checkout

    Show the add-on field value in the cart and checkout pages.

    Code:

    // Display custom add-on field in the cart
    add_filter('woocommerce_get_item_data', 'display_custom_product_addon_field_in_cart', 10, 2);
    function display_custom_product_addon_field_in_cart($item_data, $cart_item) {
        if (isset($cart_item['gift_message'])) {
            $item_data[] = array(
                'name'  => __('Gift Message', 'woocommerce'),
                'value' => $cart_item['gift_message'],
            );
        }
        return $item_data;
    }
    

    Step 5: Save the Add-On Field to the Order

    Save the add-on field value to the order metadata.

    Code:

    // Save custom add-on field to order
    add_action('woocommerce_checkout_create_order_line_item', 'save_custom_product_addon_field_to_order', 10, 4);
    function save_custom_product_addon_field_to_order($item, $cart_item_key, $values, $order) {
        if (isset($values['gift_message'])) {
            $item->add_meta_data(__('Gift Message', 'woocommerce'), $values['gift_message']);
        }
    }
    

    Step 6: Display the Add-On Field in the Admin Order Details

    Show the add-on field in the order details for the admin.

    Code:

    // Display custom add-on field in the admin order
    add_action('woocommerce_admin_order_item_headers', 'display_custom_product_addon_field_in_admin_order', 10, 1);
    function display_custom_product_addon_field_in_admin_order($item) {
        $gift_message = $item->get_meta(__('Gift Message', 'woocommerce'));
        if ($gift_message) {
            echo '<p><strong>' . __('Gift Message:', 'woocommerce') . '</strong> ' . $gift_message . '</p>';
        }
    }
    

    Final Output

    1. On the Product Page: A “Gift Message” text area will appear.
    2. In the Cart and Checkout: The entered message will be displayed.
    3. In the Order Admin Panel: The admin can view the gift message under the order details.

    You can replace “Gift Message” with any other add-on field or functionality you need (e.g., dropdown, checkbox). Let me know if you need further customization!

    How to add custom meta fields to WooCommerce products.

    To add custom meta fields in WooCommerce, you typically use hooks to display and save the meta fields. Below is an example of how to add custom meta fields to WooCommerce products.

    Add Custom Meta Field to Product Page

    Here’s how you can add a custom meta field to the product edit page in the admin area and display/save the value.

    1. Add Custom Meta Field to Admin Product Page

    Add this code to your theme’s functions.php file or a custom plugin:

    // Add a custom meta field to the product edit page
    add_action('woocommerce_product_options_general_product_data', 'add_custom_meta_field_to_product');
    
    function add_custom_meta_field_to_product() {
        echo '<div class="options_group">';
        
        woocommerce_wp_text_input(
            array(
                'id'          => '_custom_meta_key',
                'label'       => __('Custom Meta Field', 'woocommerce'),
                'placeholder' => __('Enter your custom value', 'woocommerce'),
                'desc_tip'    => 'true',
                'description' => __('This is a custom meta field for the product.', 'woocommerce'),
            )
        );
        
        echo '</div>';
    }
    

    2. Save Custom Meta Field Value

    Save the custom meta field value when the product is updated:

    add_action('woocommerce_process_product_meta', 'save_custom_meta_field');
    
    function save_custom_meta_field($post_id) {
        $custom_field_value = isset($_POST['_custom_meta_key']) ? sanitize_text_field($_POST['_custom_meta_key']) : '';
        update_post_meta($post_id, '_custom_meta_key', $custom_field_value);
    }
    

    3. Display Custom Meta Field on the Product Page

    To display the custom meta field on the front end (e.g., single product page), use the following code:

    add_action('woocommerce_single_product_summary', 'display_custom_meta_field_on_product_page', 25);
    
    function display_custom_meta_field_on_product_page() {
        global $product;
    
        $custom_value = get_post_meta($product->get_id(), '_custom_meta_key', true);
    
        if (!empty($custom_value)) {
            echo '<p class="custom-meta">' . esc_html__('Custom Meta: ', 'woocommerce') . esc_html($custom_value) . '</p>';
        }
    }
    

    Notes

    1. Replace '_custom_meta_key' with your actual meta key name.
    2. Use woocommerce_wp_checkbox, woocommerce_wp_select, etc., if you want other types of fields like checkboxes or dropdowns.
    3. For styling or additional functionality, enqueue your custom CSS/JS in the theme or plugin.

    Let me know if you need help extending this further!

    How to get all post in wordpress

    To retrieve all posts in WordPress, you can use the WP_Query class or helper functions like get_posts() or get_pages(). Here’s how you can do it:


    1. Using WP_Query (Recommended for Advanced Queries)

    The WP_Query class allows you to fetch posts with a lot of customization options.

    Basic Example

    <?php
    $args = array(
        'post_type'      => 'post', // Post type ('post' for blog posts, or custom post type slug)
        'posts_per_page' => -1,     // -1 to retrieve all posts
    );
    
    $query = new WP_Query($args);
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post(); // Setup post data
            echo '<h2>' . get_the_title() . '</h2>';
            echo '<div>' . get_the_excerpt() . '</div>';
        }
        wp_reset_postdata(); // Reset post data
    } else {
        echo 'No posts found.';
    }
    ?>
    

    Additional Query Parameters

    You can add filters to refine your query:

    • Retrieve posts by a specific category:
    $args = array(
        'category_name' => 'news', // Slug of the category
    );
    

    Retrieve posts by tag:

    $args = array(
        'tag' => 'featured', // Slug of the tag
    );
    

    Retrieve posts within a date range:

    $args = array(
        'date_query' => array(
            array(
                'after'     => 'January 1st, 2023',
                'before'    => 'December 31st, 2023',
                'inclusive' => true,
            ),
        ),
    );
    

    2. Using get_posts()

    The get_posts() function is a simpler way to retrieve posts.

    Basic Example

    <?php
    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => -1, // Retrieve all posts
    );
    
    $posts = get_posts($args);
    
    if ($posts) {
        foreach ($posts as $post) {
            setup_postdata($post); // Setup post data
            echo '<h2>' . get_the_title($post) . '</h2>';
            echo '<div>' . get_the_excerpt($post) . '</div>';
        }
        wp_reset_postdata();
    } else {
        echo 'No posts found.';
    }
    ?>
    

    3. Using get_pages()

    If you’re retrieving pages instead of posts:

    <?php
    $pages = get_pages();
    
    foreach ($pages as $page) {
        echo '<h2>' . $page->post_title . '</h2>';
        echo '<div>' . $page->post_content . '</div>';
    }
    ?>
    

    4. Using REST API (Frontend or External Use)

    If you want to fetch posts using JavaScript or for external applications, you can use WordPress’s built-in REST API.

    Endpoint for All Posts

    https://yourdomain.com/wp-json/wp/v2/posts
    

    Example Fetch Request

    fetch('https://yourdomain.com/wp-json/wp/v2/posts')
        .then(response => response.json())
        .then(data => {
            data.forEach(post => {
                console.log(post.title.rendered); // Post title
            });
        });
    

    Best Practices

    • Always call wp_reset_postdata() after custom queries to avoid conflicts with the main query.
    • Use pagination if you have a large number of posts to prevent performance issues ('posts_per_page' => 10).
    • Use caching plugins or object caching for better performance when retrieving large datasets.

    Would you like help implementing a specific method or customizing the query further?

    How to How to Custom Post in WordPress

    Creating a custom post type in WordPress allows you to organize and display specific types of content (e.g., products, testimonials, portfolio items) separately from regular posts or pages. Here’s a step-by-step guide:


    Method 1: Using a Plugin (Beginner-Friendly)

    1. Install a Plugin for Custom Post Types
      • Go to Plugins > Add New.
      • Search for Custom Post Type UI or similar plugins.
      • Install and activate the plugin.
    2. Create a Custom Post Type
      • Navigate to CPT UI > Add/Edit Post Types.
      • Fill in the required fields:
        • Post Type Slug: e.g., portfolio (lowercase, no spaces).
        • Plural Label: e.g., Portfolios.
        • Singular Label: e.g., Portfolio.
      • Configure settings, such as:
        • Enable archives.
        • Add support for features like title, editor, featured image, etc.
      • Save the post type.
    3. Display the Custom Post Type
      • The new custom post type will appear in your WordPress admin menu. You can create and manage content like regular posts.
    4. Customize Frontend Display
      • Use a page builder like Elementor, or manually edit your theme files to display the custom post type.

    Method 2: Adding Code to Your Theme (Advanced)

    For more control, you can register a custom post type using code. Add the code to your theme’s functions.php file or a custom plugin.

    1. Add the Code
    function my_custom_post_type() {
        $labels = array(
            'name'               => _x( 'Portfolios', 'post type general name' ),
            'singular_name'      => _x( 'Portfolio', 'post type singular name' ),
            'menu_name'          => _x( 'Portfolios', 'admin menu' ),
            'name_admin_bar'     => _x( 'Portfolio', 'add new on admin bar' ),
            'add_new'            => _x( 'Add New', 'portfolio' ),
            'add_new_item'       => __( 'Add New Portfolio' ),
            'new_item'           => __( 'New Portfolio' ),
            'edit_item'          => __( 'Edit Portfolio' ),
            'view_item'          => __( 'View Portfolio' ),
            'all_items'          => __( 'All Portfolios' ),
            'search_items'       => __( 'Search Portfolios' ),
            'not_found'          => __( 'No portfolios found.' ),
            'not_found_in_trash' => __( 'No portfolios found in Trash.' )
        );
    
        $args = array(
            'labels'             => $labels,
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'rewrite'            => array( 'slug' => 'portfolio' ),
            'capability_type'    => 'post',
            'has_archive'        => true,
            'hierarchical'       => false,
            'menu_position'      => null,
            'supports'           => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' )
        );
    
        register_post_type( 'portfolio', $args );
    }
    add_action( 'init', 'my_custom_post_type' );
    • Refresh Permalinks
      • After adding the code, go to Settings > Permalinks in the WordPress dashboard and click Save Changes to refresh the permalinks.
    • Customize Frontend Templates
      • WordPress uses specific templates to display custom post types:
        • single-{post_type}.php for single items.
        • archive-{post_type}.php for archives.
      • Example: For a post type called portfolio, create single-portfolio.php and archive-portfolio.php in your theme directory.
    • Query and Display
        • Use a query in your theme to display custom post types:
      $args = array(
          'post_type' => 'portfolio',
          'posts_per_page' => 10,
      );
      $portfolio_query = new WP_Query( $args );
      
      if ( $portfolio_query->have_posts() ) {
          while ( $portfolio_query->have_posts() ) {
              $portfolio_query->the_post();
              the_title();
              the_content();
          }
          wp_reset_postdata();
      } else {
          echo 'No portfolios found.';
      }
      

    Additional Tips

    Use ACF (Advanced Custom Fields) to add custom fields to your post type for more functionality.
    Use Taxonomies to organize your custom post types. Register custom taxonomies using code or a plugin.

    Would you like help with creating templates or setting up specific functionality for your custom post type?