WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to build kind of a filtering system for the events displayed on my website. I've made a custom post type 'Event', with a 'City' field. On my 'calendar' template page, I'm gathering all the events like this :

$querystr = "
    SELECT *
    FROM $wpdb->posts wposts, $wpdb->postmeta metastart
    WHERE wposts.ID = metastart.post_id
    AND metastart.meta_key = '_cp_date'
    AND wposts.post_type = 'Event'
    AND wposts.post_status = 'publish'
    AND metastart.meta_value >= DATE_FORMAT(CURRENT_DATE(), '%m/%d/%Y')
    ORDER BY metastart.meta_value ASC
$events = $wpdb->get_results($querystr, OBJECT);

And then, the loop displaying them.

What I would like to do, is to have buttons that would, on click, run another SQL query with a match on the city, and then replace the content with the result of that new query. I'm wondering what would be the "best" way to achieve this. Wouldn't ajax be my solution ?

share|improve this question

Yes, if you need to run WordPress/PHP functions from a button click (Javascript), you need Ajax.

In the following example, a shortcode will render a button (id="newquote") that calls an Ajax action hook (get_random_cpt). A query is done and replaces one div from that shortcode (id="randomquotes") with the results.

How to Use Ajax in a WordPress Shortcode?

share|improve this answer
Got it working, with just a simple line of code : <a href="<?php echo add_query_arg( 'city', 'Lyon' ); ?>> LYON </a> And on the php side just retrieve that new city parameter, bingo ! – user510990 Jan 11 '13 at 15:10
@user510990, without reloading the page? – brasofilo Jan 11 '13 at 15:12
it does reload of course, but that would do the trick untill I move to ajax – user510990 Jan 11 '13 at 15:48

AJAX definitely will be the right choice for you.

This article from WPTuts+ is about AJAX pagination, but also explains a lot about WordPress and AJAX.

Ajax (Asynchronous JavaScript and XML) is a web technology that allows a web page to dynamically update content without reloading the page within the browser. The website becomes more interactive and responsive with the use of this technology. Ajax is supported by almost all the visual web browsers… so today, we’ll show you how to setup some custom WordPress Pagination magic using AJAX.

Good luck!

share|improve this answer
Well actually wordpress has a add_query_arg function that helps me quite a lot ! Thanks for the link btw – user510990 Jan 11 '13 at 14:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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