How to use ajax in WordPress

WordPress is a popular content management system that allows website owners to create and manage custom post types. Custom post types can be used to display different types of content on your website, such as jobs, products, or events. In this tutorial, we will show you how to fetch the latest custom post type jobs from the WordPress backend using AJAX and display them on the frontend.

Step 1: Register Custom Post Type

The first step is to register the custom post type. You can do this by adding the following code to your functions.php file:

function create_custom_post_type() {
    register_post_type( 'jobs',
        array(
            'labels' => array(
                'name' => __( 'Jobs' ),
                'singular_name' => __( 'Job' )
            ),
            'public' => true,
            'has_archive' => true,
        )
    );
}
add_action( 'init', 'create_custom_post_type' );

This code will register a custom post type called “jobs” with the labels “Jobs” and “Job” for the plural and singular forms, respectively. The “public” parameter is set to true, which means that the custom post type will be visible to the public. The “has_archive” parameter is also set to true, which means that the custom post type will have an archive page.

Step 2: Create a Custom Template

Next, we need to create a custom template to display the jobs on the frontend. You can create a new PHP file in your theme folder called “job-listing.php” and add the following code:

<?php
/*
Template Name: Job Listing
*/
get_header(); ?>

<div id="job-listing"></div>

<?php get_footer(); ?>

This code creates a custom template called “Job Listing” and includes the header and footer files. It also adds an empty div with the ID “job-listing” where we will display the job listings.

Step 3: Fetch Jobs Using AJAX

We will use AJAX to fetch the latest jobs from the WordPress backend. To do this, we need to create a new PHP file called “fetch-jobs.php” in your theme folder and add the following code:

<?php
$args = array(
    'post_type' => 'jobs',
    'posts_per_page' => 5,
    'order' => 'DESC',
    'orderby' => 'date',
);

$jobs = new WP_Query( $args );

if ( $jobs->have_posts() ) {
    while ( $jobs->have_posts() ) {
        $jobs->the_post();
        ?>
        <div class="job">
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <div class="job-content"><?php the_excerpt(); ?></div>
        </div>
        <?php
    }
    wp_reset_postdata();
} else {
    echo 'No jobs found.';
}
?>

This code will fetch the latest 5 jobs from the “jobs” custom post type and display them on the page. It uses the WP_Query class to query the WordPress database and loop through the job posts. It also includes a check to make sure that there are jobs to display, and a message is shown if no jobs are found.

Step 4: Add AJAX Functionality

Now we need to add AJAX functionality to our custom template to fetch the latest jobs from the backend and display them on the frontend. To do this, we will use jQuery and the wp_ajax_ and wp_ajax_nopriv_ hooks provided by WordPress.

Add the following code to the functions.php file:

function fetch_jobs() {
    include 'fetch-jobs.php';
    die();
}

add_action('wp_ajax_fetch_jobs',  'fetch_jobs');
add_action('wp_ajax_nopriv_fetch_jobs', 'fetch_jobs');

This code creates a function called “fetch_jobs” that includes the “fetch-jobs.php” file we created earlier. It then uses the wp_ajax_ and wp_ajax_nopriv_ hooks to register this function with WordPress as an AJAX callback. The wp_ajax_ hook is used to register the callback for logged-in users, while wp_ajax_nopriv_ is used for non-logged-in users.

Next, we need to add the jQuery code to our custom template to trigger the AJAX request and display the jobs on the frontend. Add the following code to the “job-listing.php” file:

<script>
    jQuery(document).ready(function($){
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'post',
            data:{
                action: 'fetch_jobs',
            },
            success: function(data){
                $('#job-listing').html(data);
            },
            error: function(error){
                console.log(error);
            }
        });
    });
</script>

This code uses jQuery to make an AJAX request to the “admin-ajax.php” file, which is used by WordPress to handle AJAX requests. It sets the “action” parameter to “fetch_jobs” to specify which AJAX callback to call. When the request is successful, it displays the fetched jobs by inserting the HTML returned by the “fetch-jobs.php” file into the “job-listing” div. If there is an error, it logs the error to the console.

That’s it! You should now be able to fetch the latest custom post type jobs from the WordPress backend using AJAX and display them on the frontend. You can customize the code to fit your specific needs, such as changing the number of jobs displayed or the layout of the job listings.

Leave a Comment

Your email address will not be published. Required fields are marked *