Is this the right way to use ajax with sage 10?

Hello guys,

Im wondering if this is the right way to use Ajax with sage 10:



namespace App;

class Ajax
    public function __construct()
        add_action('wp_ajax_my_posts', [$this, 'my_posts']);
        add_action('wp_ajax_nopriv_my_posts', [$this, 'my_posts']);

    public function my_posts()
        $catName = $_POST['category'];

        $ajaxposts = new \WP_Query([
            'post_type' => 'post',
            'posts_per_page' => -1,
            'category_name' => $catName,
            'orderby' => 'menu_order',
            'order' => 'desc',
        $response = '';

        if ($ajaxposts->have_posts()) {
            while ($ajaxposts->have_posts()) : $ajaxposts->the_post();

                $response .= \Roots\view('partials.list-item');

        } else {
            $response = 'empty';

        echo $response;

new Ajax();


/* Ajax call */
(function ($) {
  jQuery(function ($) {
    $('.cat-list_item').on('click', function () {

        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
        dataType: 'html',
        data: {
          action: 'my_posts',
          category: $(this).data('slug'),
        success: function (res) {

I then added ajax to collect array in bootstrap/app.php

It works fine but, Im i doing it the right way ?


Just my two cents here - and this of course is always the choice of the developer.
But for some functionality I think it would make more sense to put it into a site-specific plugin and not the theme. Is the ajax used purely for visual/presentation by the theme?

Thank you @strarsis
This functionality is exclusively related to theme, so i’ll keep it there :slight_smile:

This topic was automatically closed after 42 days. New replies are no longer allowed.