WP Category Filtering of Post through AJAX JavaScript or something else

#Objective

When the user chooses a category from the drop-down, the posts should filter based on the category selection.

The existing code looks something like this. This could be some other clue.

<div class="latest_video">
	<?php wp_dropdown_categories(); ?>
	
	<?php
	// the query
		$the_query = new WP_Query( array(
		'post_type' => 'post',
		'posts_per_page' => 10,
		'post_status' => 'publish',
		'category_name' => $_GET['cat']
		)  );
	?>
	<?php if ( $the_query->have_posts() ) : ?>
		<!-- the loop -->
		<ul class="flex">
		<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
			<li class="thebox">
				<div class="imgx"><?php the_post_thumbnail( 'large') ?></div>
				<div class="texts">
					<h4><?php $categories = get_the_category();
					if ( ! empty( $categories ) ) {
					  echo '<a class="themecolor" href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">'  . esc_html( $categories[0]->name ) . '</a>';
					} ?></h4>
					<h3><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
				</div>
			</li>
		<?php endwhile; ?>
		</ul>
		<!-- end of the loop -->
		<!-- <?php wp_reset_postdata(); ?> -->
	<?php endif; ?>
</div>

This will populate all the categories in a drop down menu →

<?php wp_dropdown_categories(); ?>

Is there a question?

#Question
WP Category Filtering of Post through AJAX JavaScript or something else needed.

Do you mean “Do we do WP Category Filtering of Post through Ajax and JavaScript or is something else needed?” ?

1 Like

Hi there @WebMachine
Let me clarify this →

When the user chooses a category from the drop down, the posts, for example on a widget that shows latest 25 posts, should filter based on the category selected. I can do this with PHP but that reloads the page, which I do not want. There should be some ajax or JS alternative(using REST API).

IMHO there should be a page reload as a fallback in case the JavaScript fails for some reason. In any case what you want to do will need JavaScript.

I see two choices:

  • load everything into the page when it’s first loaded and use JavaScript to selectively show / hide, enable / disable the second level inputs etc.
  • make an XHR to the server to get the wanted options based on what has happened with the first level form inputs.
2 Likes

Hi there @Mittineague,
How is that accomplished I have no idea.

Can you guide me more with the example or possibly a live code? Actually, I am naive in JQuery/Javascript.

The WP code looks like this

In the browser, it will render like this.

Hi @codeispoetry hopefully this could get you in the right direction:

var select = document.getElementById('cat');

select.addEventListener('change', function(event) {
	event.preventDefault();
	var category = select.value;
	var request = new XMLHttpRequest();
	var url = '/this/is/some/url/to/request/your/categories?categoryId=' + category;
	request.open('get', url, true);
	request.onreadystatechange = function (data) {
		if (request.status !== 200) {
			console.error('error getting data');
		} else {
			var data = request.responseText || request.reponse;
			/* 1. See possible options explained below */ 
		}
	};
	request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	request.send();
});
  1. At this point you will act accordingly depending on what kind of data you are getting back, this depends in the wordpress API, which I don’t know.
  • Potentially you will get a JSON object and then based on that you can build your HTML and replace your existing one or just replace the content bits.
  • Potentially and ideally you also have a way to request just the relevant HTML content so you don’t have to rebuild it but I don’t know how to do this in Wordpress.
  • There is another possibility which would be making a request to the same URL with the new category, which will inevitably return you the whole page content (not the most optimal). Possibly injecting it into a document fragment without attaching it to the dom and then selecting with JS the node you’re interested in and injecting that in the dom.

A problem you very probably will face is that once you inject the HTML any JS that had been previously applied to that content won’t be initialised then and you’ll have to handle this manually.

disclaimer: This is not a beginner’s exercise but if you try hard you’ll learn a lot. Good luck

2 Likes

Hi there,

This looks like to be the complete solution for the WP →

But I could not completely understand this.

Which parts could you not understand?
I’m sure if you expand on it someone would be able to help you. As I said before the problem is not easy so you might want to help others a little more in helping you.

As a first step I would look into how the Wordpress API works and find out the way in which you can visit a custom URL that would return you just the content you’re interested in, without the rest of HTML such as head and body… This part involves no JavaScript, just PHP… after you got this then you can move on to the next step.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.