Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Tag: REST API

REST API: authenticate with Application Passwords

Posted on August 19, 2025 By Admin No Comments on REST API: authenticate with Application Passwords

REST API: Authenticate with Application Passwords

When working with the WordPress REST API, authentication is essential to securely access or modify site data. One straightforward method is using Application Passwords, a built-in WordPress feature that allows external applications or scripts to authenticate without exposing your main user password. This tutorial explains how to authenticate REST API requests using Application Passwords, including practical code examples and testing tips.

When to Use Application Passwords for REST API Authentication

  • External integrations: When connecting third-party apps or services to your WordPress site.
  • Custom scripts: Automating tasks or data synchronization without manual login.
  • Limited access: Granting specific permissions without sharing your main password.
  • Security: Application Passwords can be revoked individually, improving control over API access.

Quick Fix: Authenticate REST API Requests with Application Passwords

  1. Create an Application Password for your user in WordPress admin.
  2. Use Basic Authentication with your username and Application Password in the REST API request header.
  3. Test the authentication with a simple GET request to a REST API endpoint.
  4. Optionally, add helper code to your functions.php or a mini-plugin to customize or extend authentication behavior.

Why This Happens

WordPress REST API requires authentication for endpoints that modify data or access sensitive information. Traditional methods like cookie authentication or OAuth can be complex or unsuitable for external apps. Application Passwords provide a simple, secure alternative by generating unique passwords tied to specific users, which can be used in HTTP Basic Auth headers. This method is supported natively since WordPress 5.6.

Step-by-step: Authenticate REST API with Application Passwords

1. Create an Application Password in WordPress

  1. Log in to your WordPress admin dashboard.
  2. Go to Users > Profile (or Users > Your Profile).
  3. Scroll down to the Application Passwords section.
  4. Enter a name for the new password (e.g., “API Access Script”) and click Add New Application Password.
  5. Copy the generated password immediately; you won’t see it again.

2. Use Basic Authentication with the REST API

Include the username and Application Password in the HTTP Authorization header using Basic Auth. The format is:

Authorization: Basic base64_encode( 'username:application_password' )

Example using curl (replace username and app_password accordingly):

curl --user username:app_password https://example.com/wp-json/wp/v2/posts

3. Add Optional Helper Code (functions.php or Mini-Plugin)

WordPress supports Application Passwords natively, but you can add custom validation or logging by hooking into authentication filters. Here’s a minimal example to log successful Application Password authentications:

<?php
add_filter( 'determine_current_user', function( $user_id ) {
    if ( defined( 'WP_APPLICATION_PASSWORDS_TESTING' ) && WP_APPLICATION_PASSWORDS_TESTING ) {
        error_log( 'User ID ' . $user_id . ' authenticated via Application Password.' );
    }
    return $user_id;
}, 20 );
?>

Add this code to your theme’s functions.php or create a mini-plugin by placing it in a PHP file inside wp-content/plugins/ and activating it.

4. Test the Authentication

Use a REST client like Postman, Insomnia, or curl to test your authentication:

  • Set the request method (GET, POST, etc.) and URL (e.g., https://example.com/wp-json/wp/v2/posts).
  • Use Basic Auth with your WordPress username and the Application Password.
  • Send the request and verify you receive a valid response without authentication errors.

Variations and Additional Tips

  • Revoking Application Passwords: You can revoke any Application Password from the user profile to immediately disable access.
  • Multiple passwords: Generate multiple Application Passwords for different apps or scripts.
  • Custom endpoints: Application Passwords work with custom REST API endpoints that require authentication.
  • HTTPS recommended: Always use HTTPS to protect your credentials during transmission.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.6 and later (native Application Password support)
PHP Versions PHP 7.0+ (recommended 7.4+)

FAQ

Q1: Can I use Application Passwords with custom REST API endpoints?
Yes. Application Passwords authenticate the user making the request, so any REST API endpoint that requires authentication will accept them.
Q2: What if my Application Password is compromised?
Immediately revoke the compromised Application Password from your user profile. This disables access without affecting your main user password.
Q3: Can Application Passwords be used for non-REST API authentication?
No. They are specifically designed for REST API and XML-RPC authentication.
Q4: How do I encode the Authorization header manually?
Base64 encode the string username:application_password. For example, in PHP: base64_encode('username:app_password').
Q5: Are Application Passwords supported on multisite installations?
Yes, Application Passwords work on multisite, but each user manages their own passwords per site.
…
Developer Snippets

Register a custom post type with REST & archive

Posted on August 19, 2025 By Admin No Comments on Register a custom post type with REST & archive

Register a Custom Post Type with REST & Archive in WordPress

When building a WordPress site, you often need to create custom content types beyond posts and pages. Registering a custom post type (CPT) with REST API support and archive pages enables you to manage and display this content efficiently, especially when using headless setups or custom themes. This tutorial shows you how to register a custom post type with REST and archive capabilities using clean, copy-paste-ready code.

When to Use a Custom Post Type with REST & Archive

  • Custom Content Organization: When you want to separate content like portfolios, testimonials, products, or events from regular posts.
  • REST API Integration: If you plan to use the WordPress REST API to fetch or manipulate your custom content in JavaScript apps or external systems.
  • Archive Pages: When you want an automatically generated archive page listing all items of your custom post type.

Quick Fix: Register a Custom Post Type with REST & Archive

  1. Add the provided PHP code snippet to your theme’s functions.php file or create a mini-plugin.
  2. Visit the WordPress admin to confirm the new post type menu appears.
  3. Test the REST API endpoint and archive page.

Why This Happens

By default, WordPress supports posts and pages. To handle other content types, you must register a custom post type using register_post_type(). Enabling 'show_in_rest' =true makes the CPT accessible via the REST API. Setting 'has_archive' =true tells WordPress to generate an archive page for this CPT, allowing visitors to browse all items.

Step-by-step: Registering a Custom Post Type with REST & Archive

Below is a complete example registering a custom post type called book. This CPT supports REST API access and has an archive page.

<?php
function register_book_post_type() {
    $labels = array(
        'name'                  => _x( 'Books', 'Post type general name', 'textdomain' ),
        'singular_name'         => _x( 'Book', 'Post type singular name', 'textdomain' ),
        'menu_name'             => _x( 'Books', 'Admin Menu text', 'textdomain' ),
        'name_admin_bar'        => _x( 'Book', 'Add New on Toolbar', 'textdomain' ),
        'add_new'               => __( 'Add New', 'textdomain' ),
        'add_new_item'          => __( 'Add New Book', 'textdomain' ),
        'new_item'              => __( 'New Book', 'textdomain' ),
        'edit_item'             => __( 'Edit Book', 'textdomain' ),
        'view_item'             => __( 'View Book', 'textdomain' ),
        'all_items'             => __( 'All Books', 'textdomain' ),
        'search_items'          => __( 'Search Books', 'textdomain' ),
        'parent_item_colon'     => __( 'Parent Books:', 'textdomain' ),
        'not_found'             => __( 'No books found.', 'textdomain' ),
        'not_found_in_trash'    => __( 'No books found in Trash.', 'textdomain' ),
        'featured_image'        => _x( 'Book Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'set_featured_image'    => _x( 'Set cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'remove_featured_image' => _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'use_featured_image'    => _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'archives'              => _x( 'Book archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'textdomain' ),
        'insert_into_item'      => _x( 'Insert into book', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'textdomain' ),
        'uploaded_to_this_item' => _x( 'Uploaded to this book', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'textdomain' ),
        'filter_items_list'     => _x( 'Filter books list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'textdomain' ),
        'items_list_navigation' => _x( 'Books list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'textdomain' ),
        'items_list'            => _x( 'Books list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'books' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 5,
        'menu_icon'          => 'dashicons-book',
        'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
        'show_in_rest'       => true,
        'rest_base'          => 'books',
        'rest_controller_class' => 'WP_REST_Posts_Controller',
    );

    register_post_type( 'book', $args );
}
add_action( 'init', 'register_book_post_type' );

How to Add This Code

You can add the above code in two ways:

  1. functions.php:
…
Developer Snippets

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme

    Also by the maker of MySurveyReviews.com