jQuery and Ajax in WordPress Plugins – Public Pages

My previous post teaches you how to use jQuery and Ajax for the administration pages in your WordPress plugins. To use them in your user-facing pages requires a few changes.

We’ll use here a simlarly contrived example. Let’s say you use <!--more--> in your longer posts so they don’t fill up too much of your page. Normally, clicking the “Read more…” (or whatever text you use) link takes the user to a separate page with the complete post. In our example, rather than sending the reader to a new page, we’ll make an Ajax request to get the rest of the post and insert it directly into the current page.

Step 1: A Standard WordPress Template

Somewhere in your template, you’ll find a section like:

<div class="entry">
  < ?php the_content('Read more...'); ?>
</div>

This displays the contents of your post, with the “Read more…” link at the end to read whatever was cut off by <!--more-->. Pretty simple.

Step 2: Get the Full Post

Now it’s time to start writing our plugin. We’ll call it “Post Expander”, so our plugin file will be called post-expander.php.

We need a function that will return just the contents of a post. For example:

function post_expander_show_post (  ) {
  if ( have_posts() ) {
    while ( have_posts() ) {
      the_post();
      the_content('Read more...');
    }
  }
  die();
}

This function will take advantage of the WordPress loop, printing out just the contents of the post before dying.

So how and when do we call this function? First, we use the init hook to see if the requested posted our special post_expander variable.

function post_expander_activate ( ) {
  if ( isset( $_POST["post_expander"] ) ) {
    add_action( 'wp', 'post_expander_show_post' );
  }
}
 
add_action('init', 'post_expander_activate');

If the variable is set, we attach post_expander_show_post to the wp hook, which runs after posts are loaded but before any templates are executed. Now, if a page is requested with the post_expander variable posted, this plugin will intercept the request.

Step 3: Write the JavaScript Function

So we need a JavaScript function to post that request and insert the full post into the page. We’ll put that code in post-expander.js.

jQuery(document).ready( function($) {
  $(".more-link").click( function() {
    var link = $(this);
    $.post(link.attr("href"), {
        post_expander: 1
      }, function(data) {
        link.parents(".entry").html($(data));
      }
    );
    return false;
  });
});

Pretty simple JavaScript, that. (NB: link.parents(".entry") makes the assumption that the body of your post is in a div with the class entry.)

Step 4: Load Your JavaScript into the Page

Just a bit of housekeeping left, now. We need to load our JavaScript into the page, taking care to mention that it requires jQuery.

function post_expander_list_scripts ( ) {
  wp_enqueue_script( "post-expander", path_join(WP_PLUGIN_URL, basename( dirname( __FILE__ ) )."/post-expander.js"), array( 'jquery' ) );
}
 
add_action('wp_print_scripts', 'post_expander_list_scripts');

Once again, this plugin is not entirely practical, but you’re welcome to download the full code.

24 Responses to jQuery and Ajax in WordPress Plugins – Public Pages

  1. Pingback: How to Create A Sliding Panel with Jquery | Simply Net Dev

  2. Pingback: CSS for jQuery Selectors - It really is just CSS | Simply Net Dev

  3. Pingback: Wordpress UK » x + 3 - jQuery and Ajax in WordPress Plugins - Public Pages

  4. Pingback: The Ultimate Guide to Building a Wordpress Plugin - NETTUTS

  5. Pingback: Cotton Rohrscheib - Blog Archive » Building a Wordpress Plugin

  6. Pingback: Duymadim.com

  7. Bryan says:

    Do you have a working example to view?

  8. Polin says:

    Excelente información, con esto creare un videotutorial. Saludos

  9. Pingback: » wordpress eklentisi olu?turma rehberi

  10. Pingback: » wordpress eklentisi olu?turma rehberi

  11. Pingback: WordPress Eklentisi Olu?turma Rehberi | Webmaster Ar?ivi | Script Download | Tema Download

  12. Lee Willis says:

    Great post – your little trick for hooking code in the runs after WordPress is set up but before it outputs anything for providing the server-side of the AJAX call is perfect.

    I’ve also used it for plugins that generate image data, and / or downloadable files, e.g. CSV reports, XML downloads.

    It amazes me that this isn’t covered in the Codex!

    Great post.

  13. poosk says:

    Could this be done with the comment links as well? CHEERS!

  14. Pingback: Crear un Plugin WordPress | Todo Tutoriales web

  15. Jay says:

    I tried to modify this idea to update post content, but the $post array is never established by the_post(); so I can’t get attachments or make additional calls to get data with $post->ID

    any idea why this happens?

  16. @Jay: Without more details I can’t really be sure what’s causing your problem. Where are you trying to use $post? Is the $post variable within your current scope? If not, you might need to declare global $post; before you try to access it.

  17. Thanks a lot for such a step by step guide. This helped me a lot! Thanks buddy :)

  18. Pingback: Plugin Resources « WordPress Codex

  19. ZHAO Xudong says:

    after i make a little change,it works now.thanks any way.

    $(".more-link").live('click', function(e){
    e.preventDefault();
    var link = $(this);
    $.post(link.attr("href"), {
    post_expander: 1
    }, function(data) {
    link.parents(".post-content").html($(data));
    }
    );
    return false;
    });

  20. ZHAO Xudong says:

    add_action( 'wp', 'post_expander_show_post' );
    looks like this ‘post_expander_show_post’ function just replace the all other things.really do not know how it works.i will read more.

  21. Mas says:

    I tried to add some text after content in your code , like :
    the_content();
    echo “some text “;
    but it doesn’t work , what’s wrong in my code ?

  22. Pingback: Reparar y Arreglar » Informática – Tema: Crear un Plugin Wordpress

  23. Pingback: Coding A Wordpress Plugin Start to Finish | Coding Webs

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">