Get posts by category via ajax

In my page-members.php I output my list of categories

?php
    $args = array(
        'orderby' = 'slug'
    );
    $categories = get_categories($args);
    foreach ($categories as $category) {
        echo 'a href="' . get_category_link($category-term_id) . '"div class="category-block"' . $category-name . '/div/a';
    }
?

I'd like for a click on those links to fill the right column with the posts of that category.

I have a js file loaded for this page; my functions.php:

if (is_page()) {
    global $post;
    if ($post-post_name == 'members') {
        wp_enqueue_script('jquery', get_template_directory_uri() . '/js/jquery.js', array(), '', true);
        wp_enqueue_script('blog', get_template_directory_uri() . '/js/blog.js', array('jquery'), '', true);
        wp_localize_script('blog', 'ajaxposts', array(
            'ajaxurl' = admin_url('admin-ajax.php')
        ));
    }
}

My blog.js loads appropriately only on the members page.

What can I put into blog.js to load posts by category?

Topic ajax Wordpress

Category Web


Add the category ID to category list items <div class="category-block" data-cid="{ID-OF-CAT}">, you will need it in the ajax request. You must also include action in the request and display received data.

Here you can read more about AJAX in WP.

blog.js

(function($) {
    $(document).ready(function() {
        var cat_buttons = $(".category-block");
        cat_buttons.on( 'click', function(event){
            // 
            event.preventDefault();
            var cid = $(this).data('cid');
            $.ajax({
                type: "POST",
                url: ajaxposts.ajaxurl,
                data: {
                    action: 'my_action_name',
                    cat_id: cid // <-- category ID of clicked item / link
                }
            })
            .done( function(data){
                // display posts
            });
        });
    });
})(jQuery);

You need also PHP function to handle the AJAX request:

functions.php

add_action( 'wp_ajax_my_action_name', 'ajx_handle_my_action' );
add_action( 'wp_ajax_nopriv_my_action_name', 'ajx_handle_my_action' );

function ajx_handle_my_action() {
    $category_id = (int)$_POST['cat_id'];
    //
    // read category posts

    echo json_encode( $result );    
    wp_die();
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.