In WordPress, making an AJAX request is slightly different due to the way the platform handles backend requests. Let's walk through an example where we perform an AJAX request in a WordPress blog post to fetch a "Hello World" message using the WordPress AJAX API.
-
Steps:
- **Set up the AJAX handler in PHP (functions.php or custom plugin).
- **Use JavaScript/jQuery in your blog post or theme to make the request.**
Set Up the AJAX Handler in `functions.php`:
Add the following code to your theme's `functions.php` file or inside a custom plugin. This sets up the AJAX handler for both logged-in and logged-out users.
// Enqueue the script to be used on the front-end function my_enqueue_ajax_script() { wp_enqueue_script('my-ajax-script', get_template_directory_uri() . '/js/my-ajax.js', array('jquery'), null, true); // Localize script to pass AJAX URL to JS wp_localize_script('my-ajax-script', 'my_ajax_obj', array( 'ajax_url' => admin_url('admin-ajax.php') // Required to call AJAX in WordPress )); } add_action('wp_enqueue_scripts', 'my_enqueue_ajax_script'); // The function to handle the AJAX request function my_ajax_handler() { // Output 'Hello World' when the AJAX request is received echo 'Hello World from AJAX!'; wp_die(); // End the request properly } // Set up for logged-in users add_action('wp_ajax_my_ajax_action', 'my_ajax_handler'); // Set up for non-logged-in users add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_handler');
Explanation:
- `wp_localize_script`: This function passes the `admin-ajax.php` URL to the JavaScript file, which is needed to make the AJAX call. - `wp_ajax_` and `wp_ajax_nopriv_`: These hooks handle AJAX requests for logged-in and logged-out users, respectively. - The `my_ajax_handler()` function outputs the "Hello World" message when called via AJAX.
2. **Create the JavaScript File (`my-ajax.js`):
You will create this JavaScript file inside your theme's `js` directory (create the directory if it doesn't exist). This script will send the AJAX request when a button is clicked.
javascript
jQuery(document).ready(function($) { // When the button is clicked $('#fetch-message').on('click', function() { $.ajax({ url: my_ajax_obj.ajax_url, // The AJAX URL provided by wp_localize_script type: 'POST', // Method data: { action: 'my_ajax_action' // The action name set in the PHP handler }, success: function(response) { $('#response').html('' + response + '
'); // Show the response }, error: function() { $('#response').html('Something went wrong.
'); } }); }); });
3. **Add the HTML to Your Blog Post:
You can include this HTML inside any WordPress page or post using the Gutenberg editor or classic editor.
<p>Click the button below to get a message via AJAX:</p> <button id="fetch-message">Get Message</button> <div id="response"></div>
Make sure the `my-ajax.js` file is properly enqueued in your theme or plugin.
4. **Final Folder Structure Example (Theme):** ``` /your-theme/ functions.php /js/ my-ajax.js
5. **How It Works:
1. When the button is clicked, the JavaScript sends an AJAX request to the `admin-ajax.php` file using the action `my_ajax_action`. 2. WordPress routes the request to the `my_ajax_handler()` function defined in `functions.php`. 3. The handler sends back "Hello World from AJAX!", which is displayed inside the `<div id="response">`.
This setup enables you to make a simple AJAX request within WordPress, following its API and security best practices.Also Read:
If you're customizing your WordPress site, you might also like How to Create a Custom Contact Page.
If you liked this guide or have any questions, feel free to leave a comment! Don't forget to subscribe to my YouTube channel for more tutorials: SK NetKing YouTube Channel.
2 Comments
simple file upload in media library in wordpress ----
ReplyDeletefunction short_code(){
ob_start();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone-min.js"></script>
<link href="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone.css" rel="stylesheet" type="text/css" />
<form enctype="multipart/form-data" id="image-upload-form">
<input type="file" id="image-file" accept="image/*" />
<button type="button" id="upload-button">Upload Image</button>
</form>
<script>
jQuery(document).ready(function ($) {
$('#upload-button').on('click', function () {
var formData = new FormData();
var fileInput = $('#image-file')[0].files[0];
if (fileInput) {
formData.append('file', fileInput);
formData.append('action','image_upload');
$.ajax({
url: 'http://testingdemo.great-site.net/wp-admin/admin-ajax.php', // Replace with your WordPress admin-ajax.php URL
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
var myObj = JSON.parse(response);
if(myObj['status']=='success'){
alert('success');
}
}
});
} else {
$('#message').html('Please select an image file.');
}
});
});
</script>
<?php
return ob_get_clean();
}
add_shortcode( "upload_img","short_code" );
//php handlig code here =
function handle_image_upload() {
if (isset($_FILES['file'])) {
$file = $_FILES['file'];
// Upload the image and get the attachment ID
$filename = sanitize_file_name($file['name']);
$attachment_id = media_handle_upload('file', 0);
echo json_encode(array('post_id'=>$attachment_id,'status'=>'success'));
} else {
echo json_encode(array('error'=>'not uploaded'));
}
die();
}
add_action('wp_ajax_image_upload', 'handle_image_upload');
add_action('wp_ajax_nopriv_image_upload', 'handle_image_upload');
wp query all possible parameters
ReplyDeleteI'd be glad to provide details on WP_Query arguments:
WP_Query Arguments
WP_Query offers a rich set of arguments to tailor your post retrieval and display. Here's a breakdown of some common arguments:
Post Parameters:
* posts_per_page (int): Specifies the number of posts to retrieve. Defaults to 10.
* offset (int): Sets the number of posts to skip before starting the loop.
* post_type (string/array): Filters posts by post type (e.g., 'post', 'page', 'product').
* p (int): Retrieves a post by its ID.
* name (string): Retrieves a post by its post slug.
* post__in (array): Retrieves posts by a specific set of IDs.
* post__not_in (array): Excludes posts by a specific set of IDs.
Author Parameters:
* author (int/string): Filters posts by author ID, username, or comma-separated list.
* author_name (string): Retrieves posts by author's username.
* author__in (array): Retrieves posts by a specific set of author IDs.
* author__not_in (array): Excludes posts by a specific set of author IDs.
Category Parameters:
* cat (int/string): Filters posts by category ID or slug (can include children).
* category_name (string): Filters posts by category slug (can include children).
* category__and (array): Retrieves posts that belong to all specified categories.
* category__in (array): Retrieves posts from a specific set of category IDs (no children).
* category__not_in (array): Excludes posts from a specific set of category IDs.
Tag Parameters:
* tag (int/string): Filters posts by tag ID or slug.
* tag_id (int): Retrieves posts by a specific tag ID.
* tag_slug (string): Retrieves posts by a specific tag slug.
* tag__in (array): Retrieves posts from a specific set of tag IDs.
* tag__not_in (array): Excludes posts from a specific set of tag IDs.
Taxonomies:
* tax_query (array): Enables complex queries using taxonomies (categories, tags, custom taxonomies).
Date Parameters:
* year (int): Filters posts by year.
* monthnum (int): Filters posts by month.
* day (int): Filters posts by day.
* date_query (array): Enables complex date-based queries.
Order Parameters:
* orderby (string): Sorts posts by various criteria (e.g., 'date', 'title', 'author').
* order (string): Sets ascending ('ASC') or descending ('DESC') order.
And many more...
For a comprehensive list and detailed explanations, refer to the WordPress Codex: https://developer.wordpress.org/reference/classes/wp_query/