Category: Plugin

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!

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!