Mícéal Gallagher in Wordpress 6 minutes

WordPress - Using AJAX to query WordPress post titles

AJAX is a great technique for retrieving server data when you don’t want to refresh a web page. When done right, AJAX can be used to great effect. In the scenario where we want a user to be able to select an option from a drop down list, based on their selection, query the WordPress database for either the oldest or newest post title. AJAX can be fired under one of two conditions - privileged and non-privileged users. We need to add a hook to WordPress so that it will accept a request under both of these conditions. I’ll be adding all this code to my theme’s functions.php file but I would recommend including your PHP code in a separate file. Notice in the code below that add_action takes two parameters; the first is the name of the PHP method including either a wp_admin_ or wp_ajax_nopriv_ prefix and the second is the name of the function that is called to satisfy the request. You can probably guess that the prefix denotes how your PHP method will be available for privileged or non-privileged users.

```phpadd_action( ‘wp_ajax_get_first_or_last_post_title’, ‘get_first_or_last_post_title’ ); add_action( ‘wp_ajax_nopriv_get_first_or_last_post_title’, ‘get_first_or_last_post_title’);


Now let's create our PHP function so it will satisfy our AJAX request. We'll get the value of the `first_or_last` parameter from the AJAX request to determine what post title to return; this is accomplished using `$_POST`.

```defaultfunction get_first_or_last_post_title() {
    // Get the parameter value from our request
    $firstOrLast = $_POST['first_or_last'];
    if ( "first" == $firstOrLast ) {
        $order = "DESC";
    } else if ( "last" == $firstOrLast ) {
        $order = "ASC";
    }
    $args = array(
        'numberposts' => '1',
        'orderby' => 'post_date',
        'order' => $order
    );
    $posts = wp_get_recent_posts( $args );
    $postId = $posts[0]["ID"];
    $postTitle = $posts[0]["post_title"];
    $href = get_permalink($postId);
    echo "<a href='" . $href . "'>" . $postTitle . "</a>";
    die();
}

With a drop down list on the webpage containing the two options (first and last) and a DIV with the id divPostTitle (so that we can display the returned post title), we will add a change event to the drop down list to fire the AJAX request.

```javascript$(document).ready(function() { $(“#lstFirstOrLast”).change(function() { getFirstOrLastPost(); }); });


Now the `getFirstOrLastPost` function:

```javascriptfunction getFirstOrLastPost() {
    var selectedValue = $("#lstFirstOrLast").val();
    if ("NON" != selectedValue) {
        jQuery.ajax({
            type: "post",
            dataType: "text",
            url: "http://mehaul.me/wp-admin/admin-ajax.php",
            data: ({
                action: "get_first_or_last_post_title",
                first_or_last: selectedValue
            }),
            success: function(data, textStatus, XMLHttpRequest) {
                var divPostTitle = $('#divPostTitle');
                divPostTitle.html(data);
            },
            error: function(xhr, textStatus, errorThrown) {
                alert(errorThrown);
            }
        })
    }
}

Put it all together and we’ve got a working example…

Example - Display link to first or last post