I create Recent posts widget and i trying to create load more button for it to get more Recent posts links by ajax ,is there any tutorial for how to make it?


Look at WordPress's documentation on AJAX

In your theme or plugin, you'll want to have code like:

add_action('wp_ajax_my_load_recent', 'my_load_recent_posts');
add_action('wp_ajax_nopriv_my_load_recent', 'my_load_recent_posts');
function my_load_recent_posts() {
    $args = array(
        /* Arguments go here, i.e. how many posts to get */
    query_posts($args); /* [1] */

    /* Header wrap output */
    if (have_posts()) : while (have_posts()) : the_post(); /* [2] */
        /* Output for each post */
    endwhile; else :
        /* Output for if there are no posts to get */
    /* Footer wrap output */


[1] query_posts() documentation

[2] Wordpress loop documentation

Then to reach this function you'll want to have on your front end, assuming you're using jQuery:

$.ajax(ajax_url/* [3] */, {
    method: 'POST',
    data: {
       action: 'my_load_recent',
    success: function(response) {
        /* handling of the output returned by PHP function */
    error: function() {
        /* what to do if there's a server error, like 404

[3] See WordPress's documentation on AJAX to generate the ajax_url: "As this article suggests, use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url('admin-ajax.php')"

| improve this answer | |
  • this is good but i need to create button called Load more when clicked get me the next posts links list ,like twitter.com – Mohamed Badawy Aug 29 '13 at 18:06
  • You can do this easily with my instructions, you make your button trigger the JavaScript I wrote. Then you have the PHP output li's with linked titles using the_permalink() and the_title(), then you append the response to the widget ul in your success handler. You may want to pass an offset in your AJAX call, so that you can load posts more than once. – George Yates Aug 29 '13 at 21:26
  • sorry but how to pass an offset in my AJAX call? – Mohamed Badawy Aug 29 '13 at 21:45
  • In the data parameter in your AJAX, you would pass something like: offset: 0 or offset: 5 and then in your PHP function you get that information using $_POST['offset']. Then you utilize that in your query_posts() array, by setting offset => $_POST['offset'] Just be sure to maintain the value, maybe as data on the load more button element, and increment it everytime you load more posts. – George Yates Aug 29 '13 at 21:49
  • sorry but last one question :), how to increment the offset var everytime i load more posts? – Mohamed Badawy Aug 29 '13 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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