Roots Discourse

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:

app/ajax.php:

<?php

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');

            endwhile;
        } else {
            $response = 'empty';
        }

        echo $response;
        exit;
    }
}

new Ajax();

Resources/scripts/app.js

/* Ajax call */
(function ($) {
  jQuery(function ($) {
    $('.cat-list_item').on('click', function () {
      $('.cat-list_item').removeClass('active');
      $(this).addClass('active');

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

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

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

Thanks

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: