0

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?

  • Is the second block of code inside a hook callback function? You must use wp_enqueue_scripts hook to enqueue scripts and styles. – Eduardo Escobar Aug 6 at 18:26
0

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();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.