Using WordPress ‘admin_post_nopriv_{$action}’ PHP action

The admin_post_nopriv_{$action} WordPress PHP action fires on a non-authenticated admin post request for the given action.

Usage

add_action('admin_post_nopriv_my_custom_action', 'my_custom_function');

function my_custom_function() {
    // your custom code here
}

Parameters

  • $action (string) – The action name to be executed for the non-authenticated admin post request.

More information

See WordPress Developer Resources: admin_post_nopriv_{$action}

Examples

Simple contact form submission

Create a simple contact form submission for non-authenticated users.

// In your theme's functions.php
add_action('admin_post_nopriv_submit_contact_form', 'handle_contact_form_submission');

function handle_contact_form_submission() {
    // Process the submitted contact form data
    // ...

    // Redirect the user back to the form page
    wp_redirect($_SERVER['HTTP_REFERER']);
    exit;
}

Custom search request

Create a custom search request for non-authenticated users.

// In your theme's functions.php
add_action('admin_post_nopriv_custom_search', 'handle_custom_search_request');

function handle_custom_search_request() {
    // Process the submitted search query
    // ...

    // Redirect the user to the search results page
    wp_redirect(get_search_link());
    exit;
}

Vote on a poll

Create a voting system for a poll on your website for non-authenticated users.

// In your theme's functions.php
add_action('admin_post_nopriv_vote_poll', 'handle_poll_vote');

function handle_poll_vote() {
    // Process the submitted vote data
    // ...

    // Redirect the user back to the poll page
    wp_redirect($_SERVER['HTTP_REFERER']);
    exit;
}

Submitting a comment

Create a comment submission for non-authenticated users.

// In your theme's functions.php
add_action('admin_post_nopriv_submit_comment', 'handle_comment_submission');

function handle_comment_submission() {
    // Process the submitted comment data
    // ...

    // Redirect the user back to the post page
    wp_redirect(get_permalink($_POST['post_id']));
    exit;
}

Adding a product to cart

Create an action to add a product to the cart for non-authenticated users in a custom e-commerce system.

// In your theme's functions.php
add_action('admin_post_nopriv_add_to_cart', 'handle_add_to_cart');

function handle_add_to_cart() {
    // Process the submitted product data and add to cart
    // ...

    // Redirect the user back to the product page
    wp_redirect($_SERVER['HTTP_REFERER']);
    exit;
}