Metadata API

The Metadata API is the backbone for managing custom metadata in WordPress. Metadata is simply data about data. For example, when you upload an image to a post, WordPress stores metadata like the image’s dimensions, file size, and alt text. The Metadata API provides functions to add, update, delete, and retrieve metadata for posts, users, comments, and terms.

Key Functions:

  • add_post_meta()
  • update_post_meta()
  • get_post_meta()
  • delete_post_meta()

These functions simplify handling custom fields and metadata, making it easy to store and retrieve additional information for your content.

Example:

function add_reading_time_meta($post_id) {
    // Calculate reading time (for example, 5 minutes)
    $reading_time = 5;

    // Check if the meta field already exists; if not, add it
    if (!add_post_meta($post_id, 'reading_time', $reading_time, true)) {
        // If the meta field exists, update it
        update_post_meta($post_id, 'reading_time', $reading_time);
    }
}
add_action('save_post', 'add_reading_time_meta');

To display the reading time in your post, use the get_post_meta() function:

function display_reading_time($content) {
    if (is_single()) {
        global $post;
        $reading_time = get_post_meta($post->ID, 'reading_time', true);
        if ($reading_time) {
            $content .= '<p><strong>Estimated Reading Time: ' . esc_html($reading_time) . ' minutes</strong></p>';
        }
    }
    return $content;
}
add_filter('the_content', 'display_reading_time');

If you need to update the reading time later, you can use update_post_meta():

function update_reading_time_meta($post_id, $new_reading_time) {
    update_post_meta($post_id, 'reading_time', $new_reading_time);
}

If you ever need to remove the “reading_time” metadata from a post, you can use delete_post_meta():

function delete_reading_time_meta($post_id) {
    delete_post_meta($post_id, 'reading_time');
}

Shortcode API

The Shortcode API allows you to create custom shortcodes that users can insert into posts, pages, and widgets. Shortcodes are a quick way to execute code within content without writing HTML or PHP. For example, is a built-in shortcode that displays a gallery of images.

Creating a shortcode is straightforward. Here’s an example of a basic shortcode that outputs a simple message:

function custom_greeting_shortcode() {
    return 'Hello, World!';
}
add_shortcode('greeting', 'custom_greeting_shortcode');

Users can now insert [greeting] into their posts, and WordPress will display “Hello, World!” wherever the shortcode is placed.

Administrative Menu

The Administrative Menu API enables developers to add custom menus and submenus to the WordPress admin dashboard. This is particularly useful for plugin and theme developers who need to provide an interface for their tools.

Adding a custom menu involves the add_menu_page() function, while add_submenu_page() is used for submenus. These functions allow you to specify the menu title, page title, capability required to access the page, and the callback function that renders the page content.

Here’s an example:

function custom_admin_menu() {
    add_menu_page(
        'Custom Menu', 
        'Custom Menu', 
        'manage_options', 
        'custom-menu-slug', 
        'custom_menu_page_callback'
    );
}
add_action('admin_menu', 'custom_admin_menu');

function custom_menu_page_callback() {
    echo '<h1>Welcome to the Custom Menu Page</h1>';
}

Options API

The Options API is used for storing, retrieving, and deleting options in the WordPress database. Options are pieces of data that are typically used for site-wide settings, such as the site title, tagline, or theme-specific settings.

The API provides functions like add_option(), update_option(), get_option(), and delete_option(). These functions allow you to easily manage settings for your themes or plugins.

For example, to save a custom setting:

add_option('custom_option_name', 'default_value');

function custom_save_option() {
    update_option('custom_option_name', 'new_value');
}

And to retrieve it:

$value = get_option('custom_option_name');
echo $value; // Outputs 'new_value'

Rewrite API

The Rewrite API in WordPress allows you to create custom URL structures for your content, making your URLs more readable and SEO-friendly. This API handles the routing of requests based on URL patterns, translating them into queries that WordPress understands.

The Rewrite API is especially useful when you want to create custom post types or taxonomies with specific URL structures or when you want to modify the default URL patterns for posts, pages, and archives.

Key Functions:

  • add_rewrite_rule()
  • add_rewrite_tag()
  • flush_rewrite_rules()

For example, to create a custom rewrite rule that maps a specific URL pattern to a custom template, you can use the following code:

function custom_rewrite_rule() {
    add_rewrite_rule('^custom/([^/]*)/?', 'index.php?custom_param=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_rule');

function custom_query_vars($vars) {
    $vars[] = 'custom_param';
    return $vars;
}
add_filter('query_vars', 'custom_query_vars');

In this example, visiting yourdomain.com/custom/something/ would map to the index.php file with a query variable custom_param set to something.

After adding custom rewrite rules, it’s important to flush the rewrite rules to ensure they take effect. This can be done using flush_rewrite_rules().

Widgets API

The Widgets API in WordPress allows you to create and manage custom widgets that users can add to their site’s sidebars, footers, or other widgetized areas. Widgets are small content blocks that display specific information or functionality, such as recent posts, search forms, or custom HTML.Creating a custom widget involves extending the WP_Widget class and defining its behavior in a few key methods, including __construct(), widget(), form(), and update().Key Methods:

  • __construct() – Initializes the widget, setting up its name, description, and other options.widget() – Outputs the content of the widget on the front end.form() – Handles the widget’s settings form in the admin area.update() – Saves the widget settings when updated.

class Greeting_Widget extends WP_Widget {
    function __construct() {
        parent::__construct(
            'greeting_widget',
            __('Greeting Widget', 'text_domain'),
            array('description' => __('A widget that displays a greeting message.', 'text_domain'))
        );
    }

    public function widget($args, $instance) {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }
        echo '<p>Hello, World!</p>';
        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('New title', 'text_domain');
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title:', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        return $instance;
    }
}

function register_greeting_widget() {
    register_widget('Greeting_Widget');
}
add_action('widgets_init', 'register_greeting_widget');

the Greeting_Widget class defines a simple widget that outputs a “Hello, World!” message, with a customizable title.


Thank you for reading…
By ~Leaveitblank(Mayank Tripathi)