Display products of category when it is clicked using AJAX

Question

I was able to successfully list out a bunch of subcategories on a page (page_template.php).

Where I am stuck:
Now, I want to be able to select one of those subcategories on the page and have the products associated with it appear below it. Preferably without reloading the page, which from what I have gathered means I must use AJAX.

I have been researching for a few hours and most solutions I was able to find are terribly outdated so I am hoping to get a little bit of direction here. I have not worked with AJAX before.

My page_template.php:

<section id="content" class="site-content">
<div id="seam-builder-wrap" class="container">
    <?php
        $masterCat = 39; // Master category 'Seam Builder' ID is 39)
        $taxonomyName = "product_cat";
        $termchildren = get_term_children($masterCat, $taxonomyName);
        
        foreach ($termchildren as $child) {
            $subCat = get_term_by('id', $child, $taxonomyName); //assigns $subCat to the current subcategory in the loop
            $subCat_title = $subCat->name; //gets the name of the subcategory
            $cat_id = $subCat->term_id; //gets the ID of the subcategory on its own
            $thumbnail_id = get_term_meta($child, 'thumbnail_id', true); //gets the thumbnail of the subcategory
            $image = wp_get_attachment_url($thumbnail_id); //gets the URL of the thumbnail
    ?>

    <a id="<?php echo $cat_id ?>" class="seamBuilder_trigger" href="#">
        <img src="<?php echo $image ?>" />
        <span><?php echo $subCat_title ?></span>
    </a>
        <?php } //ends for foreach loop above ?>
</div>

<div class="posts-area">
    
</div>

My functions.php


function get_products() {
    // Query Arguments
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response .= get_template_part('products');
        }
    } else {
        $response .= get_template_part('none');
    }

    echo $response;

    exit; // leave ajax call
}

// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

?>

I’m at a bit of a loss on what to do next. A short break is perhaps what my brain needs. Any help is VERY appreciated!

0
David M 2 months 0 Answers 14 views 0

Leave an answer