arraypress/wp-ajax-select

Simple, lightweight AJAX select functionality for WordPress with key/value array support

dev-main 2025-09-24 15:55 UTC

This package is auto-updated.

Last update: 2025-09-24 15:55:56 UTC


README

Simple, lightweight AJAX select functionality for WordPress with automatic asset loading and key/value array support.

Features

  • Simple Key/Value Arrays: Use associative arrays instead of complex data structures
  • Auto-initialization: Automatically initializes selects with data-ajax attribute
  • Automatic Asset Loading: CSS and JS load automatically when using helper functions
  • Lightweight: Minimal JavaScript (~250 lines) and CSS (~150 lines)
  • WordPress Native: Uses WordPress coding standards and built-in functions
  • No Dependencies: Just jQuery (already in WordPress)
  • Smart Pre-selection: Automatically fetches display text for pre-selected values
  • Customizable: Extensive data attribute configuration
  • Performance: Smart caching and debouncing for optimal performance
  • Accessibility: Keyboard navigation and ARIA support

Installation

Install via Composer:

composer require arraypress/wp-ajax-select

How It Works

Automatic Asset Loading

The library automatically enqueues CSS and JavaScript files when you use any of the helper functions. No need to manually enqueue scripts - just call wp_ajax_select() and everything loads automatically.

// This automatically loads both CSS and JS if not already loaded
echo wp_ajax_select( [
    'name' => 'user_id',
    'ajax' => 'search_users'
] );

Pre-selected Values

When you provide a data-value attribute, the library makes an AJAX request with initial_value parameter to fetch the display text for that ID:

<select data-ajax="search_posts" data-value="123"></select>

The library will call your AJAX handler with initial_value=123 to get the text for that ID.

AJAX Response Format

Your AJAX handler should return a simple associative array (key/value pairs):

wp_send_json_success( [
    '1' => 'John Doe',
    '2' => 'Jane Smith',
    '3' => 'Bob Johnson'
] );

The key becomes the option value, and the value becomes the display text.

Basic Usage

Create a Select Field

Using data attributes (auto-initialized):

<select name="user_id"
        data-ajax="search_users"
        data-placeholder="Search users..."
        data-nonce="<?php echo wp_create_nonce( 'search_users' ); ?>">
</select>

Using PHP helper:

echo wp_ajax_select( [
    'name' => 'user_id',
    'ajax' => 'search_users',
    'placeholder' => 'Search users...',
    'nonce' => wp_create_nonce( 'search_users' )
] );

Complete AJAX Handler Example

add_action( 'wp_ajax_search_users', function() {
    check_ajax_referer( 'search_users' );
    
    $search = sanitize_text_field( $_POST['search'] ?? '' );
    $initial_value = sanitize_text_field( $_POST['initial_value'] ?? '' );
    
    // Handle initial value request (for pre-selected items)
    if ( $initial_value ) {
        $user = get_user_by( 'ID', $initial_value );
        if ( $user ) {
            // Return just the requested item
            wp_send_json_success( [ 
                $user->ID => $user->display_name 
            ] );
        } else {
            wp_send_json_success( [] );
        }
        return;
    }
    
    // Build query args
    $args = [
        'number' => 20,
        'fields' => [ 'ID', 'display_name' ]
    ];
    
    // Handle numeric search (search by ID)
    if ( is_numeric( $search ) ) {
        $args['include'] = [ intval( $search ) ];
    } else if ( $search ) {
        $args['search'] = "*{$search}*";
    }
    
    $users = get_users( $args );
    
    // Return simple key/value format
    $results = [];
    foreach ( $users as $user ) {
        $results[ $user->ID ] = $user->display_name;
    }
    
    wp_send_json_success( $results );
});

Posts Example with Smart ID Search

add_action( 'wp_ajax_search_posts', function() {
    check_ajax_referer( 'search_posts' );
    
    $search = sanitize_text_field( $_POST['search'] ?? '' );
    $initial_value = sanitize_text_field( $_POST['initial_value'] ?? '' );
    
    // Handle initial value request
    if ( $initial_value ) {
        $post = get_post( $initial_value );
        if ( $post ) {
            wp_send_json_success( [ 
                $post->ID => $post->post_title 
            ] );
        } else {
            wp_send_json_success( [] );
        }
        return;
    }
    
    $args = [
        'posts_per_page' => 20,
        'post_status' => 'publish'
    ];
    
    // If search is numeric, also search by ID
    if ( is_numeric( $search ) ) {
        $args['p'] = intval( $search );
    } else if ( $search ) {
        $args['s'] = $search;
    }
    
    $posts = get_posts( $args );
    
    $results = [];
    foreach ( $posts as $post ) {
        $results[ $post->ID ] = $post->post_title;
    }
    
    wp_send_json_success( $results );
});

Request Parameters

Your AJAX handler receives these parameters:

Parameter Description
search The search term typed by the user
initial_value The ID when fetching a pre-selected value
limit Number of results requested (for initial load)
_wpnonce Security nonce

Configuration Options

Data Attributes

Attribute Default Description
data-ajax - Required. AJAX action name
data-placeholder Type to search... Input placeholder text
data-empty-option Select an option... Empty option text
data-min-length 3 Minimum characters before search
data-delay 300 Debounce delay in milliseconds
data-initial-results 20 Number of results to show initially
data-nonce - Security nonce
data-value - Pre-selected value (ID)
data-text - Pre-selected text (optional, fetched if not provided)

PHP Configuration

wp_ajax_select( [
    'name'            => 'field_name',
    'id'              => 'field_id',
    'ajax'            => 'ajax_action',
    'placeholder'     => 'Type to search...',
    'empty_option'    => 'Select an option...',
    'min_length'      => 3,
    'delay'           => 300,
    'initial_results' => 20,
    'nonce'           => wp_create_nonce( 'action' ),
    'value'           => '123',
    'text'            => 'Selected Item',
    'class'           => 'custom-class',
    'required'        => true,
    'disabled'        => false
] );

Advanced Usage

Custom AJAX URL

echo wp_ajax_select( [
    'name'     => 'external_api',
    'ajax'     => 'search_external',
    'ajax_url' => 'https://api.example.com/search'
] );

Pre-selected Values

// Just value (text will be fetched via AJAX automatically)
echo wp_ajax_select( [
    'name'  => 'post_id',
    'ajax'  => 'search_posts',
    'value' => '123'
] );

// Value and text (no extra AJAX call needed)
echo wp_ajax_select( [
    'name'  => 'post_id',
    'ajax'  => 'search_posts',
    'value' => '123',
    'text'  => 'Hello World Post'
] );

Direct Rendering

// Echo directly in templates
wp_ajax_select_render( [
    'name' => 'category_id',
    'ajax' => 'search_categories'
] );

Form Integration

<form method="post">
    <?php 
    wp_ajax_select_render( [
        'name'     => 'selected_user',
        'ajax'     => 'search_users',
        'required' => true,
        'nonce'    => wp_create_nonce( 'search_users' )
    ] );
    ?>
    <button type="submit">Submit</button>
</form>

<?php
// Handle form submission
if ( isset( $_POST['selected_user'] ) ) {
    $user_id = intval( $_POST['selected_user'] );
    // Process the selected user ID
}
?>

Helper Functions

  • wp_ajax_select( $field ) - Load assets and optionally return field HTML
  • wp_ajax_select_render( $args ) - Echo select field HTML directly

Requirements

  • PHP 7.4 or later
  • WordPress 5.0 or later
  • jQuery (included with WordPress)

License

This library is licensed under the GPL v2 or later.

Credits

Developed by ArrayPress