This code snippet filters WordPress post queries based on custom conditions, specifically by category, using the 'pre_get_posts' action hook. It is us...
Back to Snippets
php
• 39 lines
PHP
PHP
PHP
Secure AJAX Handler with Nonce Verification
Complete AJAX handler pattern with nonce verification, input sanitization, proper error handling, and script localization.
Snippet Stats
Lines
39
Characters
1,214
Read
2 mins
// Register the AJAX action for logged-in users.
add_action( 'wp_ajax_my_custom_action', 'handle_my_custom_action' );
/**
* Handle the AJAX request securely.
*
* @return void
*/
function handle_my_custom_action(): void {
// Verify the nonce.
check_ajax_referer( 'my_custom_nonce', 'security' );
// Sanitize input.
$item_id = isset( $_POST['item_id'] ) ? absint( $_POST['item_id'] ) : 0;
if ( ! $item_id ) {
wp_send_json_error( array( 'message' => __( 'Invalid item.', 'theme-domain' ) ) );
}
// Your business logic here.
$result = get_post( $item_id );
if ( ! $result ) {
wp_send_json_error( array( 'message' => __( 'Item not found.', 'theme-domain' ) ) );
}
wp_send_json_success( array(
'title' => esc_html( $result->post_title ),
) );
}
// Enqueue and localize the script.
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_script( 'my-ajax-script', get_template_directory_uri() . '/assets/js/ajax.js', array( 'jquery' ), '1.0.0', true );
wp_localize_script( 'my-ajax-script', 'myAjax', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'my_custom_nonce' ),
) );
} );
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis code snippet provides a custom WordPress hook to filter posts dynamically based on specific conditions such as post meta, categories, or tags. It...
Register a custom Gutenberg block pattern with category — reusable hero section pattern with heading, paragraph, and CTA button.