Ajax WordPress post popup with SimpleModal and jQuery

Today we are going to look at getting the content of a post using ajax and then display it in a popup box. The popup part is actually the easiest part, thanks to the fantastic Simple Modal plugin for jQuery written by Eric Martin.

So the basics here are:

  • we call a page using ajax, passing the id of the post
  • The page grabs the content of the post we requested and returns it to the script
  • We then output the content in a div and “simplemodal” it

And for the result, click on this link.

Note: be sure to dowload the latest version of both jQuery and SimpleModal.

The major problem when it comes to ajax and WordPress is that you need to call a php script that will have access to all the WordPress built in functions. The solution came from this post from John Faulds.

Basically you create a page template that will be in charge of grabbing the post from the id we pass and returning the content to the script.

This is going to be a simple loop like this:

[snippet-ajaxhandler]

Save this code in a file called ajax-handler.php in you theme folder. Now if you go in your admin panel and create a new page, you should be able to select this template as the page template. So I have created a page in WordPress called Ajax Handler with the template “Ajax Handler” assigned to it. The special function we use here, get_post(), will grab the content of a post with the Id we’ve passed with ajax as a GET variable.

Talking about ajax, lets have a look at the function to do the stuff:

[snippet-ajax]

note: in the ‘load’ function you want to use the permalink to the page NOT the path the template file of the ajax handler.

note 2: I am using ‘jQuery’ instead of $ because I use the jQuery included in WordPress which is in no conflict mode. If you use normal jQuery then replace all occurrences of ‘jQuery’ by $ in my javascript snippet. This code would go in an external javascript file you would include on your page or in the header. But the first option is recommended.

This a very simple way to do it, thanks to jQuery. This means: when a click on a link with a class postpopup, get the id from its rel attribute, create a empty div, load the page ‘ajax-handler’ and add the content of the data returned to the div. Then SimpleModal it.

The html for the link should look like this:

[snippet-link]

note: in this html it would be better to replace the href by the actual url of the post, so if someone hasn’t got javascript enable they can still view the content.

And that’s it, all done. To get everything to work you will of course need to include jQuery and SimpleModal on your page. Don’t forget to hide your ajax handler page from your blig navigation. If your theme is using the wp_list_pages function you can pass a parameter ‘exclude=id_of_the_page’ to exclude it from the list.

And for the result, click on this link.

55 thoughts on “Ajax WordPress post popup with SimpleModal and jQuery”

  1. I’ve resolved this problem )) There are was chosen another template “basic template” for the “ajax handler” page in admin panel. I forget about it )) Now it’s works fine.

  2. Thanks for the very useful post. It’s what i had looking for. I made all points that you described, but have some problem: there are no post into the modal window, just empty DOM. I found that trouble probably in my URL-settings.
    Your url of the example-post is http://wordpressthemescollection.com/ajax-handler?id=499 working fine.
    But my URL http://localhost/minwebprom/ajax-handler/?id=910 does not show needed post, just code of my template (header, sidebar, footer – all DOM). I tried to remove slash after “ajax-handler” but it inserts automatically. Do you have any ideas how to make it work fine? Thanks for help and sorry for my crooked English :)

  3. @Goobersnotch

    “This code would go in an external javascript file you would include on your page or in the header. But the first option is recommended.”

    I understand that this is not easy for beginners but I am afraid that if you do not see what you need to do when reading this you shouldn’t probably try the ajax popup thing in the first place. Now to answer your question the code goes between script tags in the head section of your theme (probably in header.php) or in an external javascript file which you have to call from the head section of your theme (probably header.php).

  4. In answer to Rod. Not sure if you got this sorted out or not, but I figured out that you also need to read the page about SimpleModal itself. You have to download and add the ‘x’ icon and add some CSS in order to get the ‘close’ icon and functionality to work. You also need to add some CSS to style the simplemodal box. There is also some great callback references information for modifying the behaviour of simplemodal. Hope this helps!

  5. This is Brilliant!!
    Sorry if i misunderstood but is there a way to ‘automatize’ the whole Post into pop up style like this?
    And can we comment on that post also?
    I mean this thing is exactly what i need, it will be nice if i can make all my post into just links and made it appear as pop-up along with the comment feature.
    Or maybe is there any plugin or such for this thing to happen?

    Anyway, this post is, again, Brilliant!

    Regards

  6. I would love to integrate this into my website. However, the best thing you can do for any non experienced person would be to paste an entire example header and link in a code script so we can see how you are calling the scripts in your header as well as an example link in the page fully, within a wordpress example theme. If you add this, please email me.

  7. Hello I think you need to be clearer on the steps as not everyone who is using this tutorial is a web programming genius. For instance, when you mention this function:

    jQuery(document).ready(function() {
    jQuery(‘a.postpopup’).click(function(){
    id = jQuery(this).attr(‘rel’);
    jQuery(”).hide().appendTo(‘body’).load(‘http://urlofyoursite.com/ajax-handler/?id=’+id).modal();
    return false;
    });
    });

    You don’t exactly tell us where to put it. I am currently stumped on this step. And I have not been able to get anything working.

  8. This tutorial is great, and I really appreciate your hard work. I’m not an expert, nor a rookie, but I found a few problems that I think could make the tutorial easiest to understand:
    – Be clear that the template needs this in order to be recognised: <?php
    /*
    Template Name: Ajax Handler
    */
    – Somewhere explain that rel="postid" should be something like rel="”, I mean, showing the ID, not the word “postid”. In the beginning I thought that maybe there was a need to put “postid” in rel so that the modal would be triggered.
    – Easiest for everyone would be to replace http://urlofyoursite.com/ajax-handler/?id='+id with <?php bloginfo('url')/ajax-handler/?id='+id . That will also prevent problems on site migrations of any kind.
    – Add a link or an explanation to "jQuery included in WordPress". I found it out, but needed to explore.

    I've been the whole day with this. If I recall something else, I'll drop another comment.
    Don't get me wrong, your post was very useful for me, that's why I wanted to contribute somehow with this.
    Bye!

  9. hi trying to implement modal ajax wordpress post popup but i am not able to end up with the soution .i found your post was very helpful for me. but i have a doubt that it supports the view count on modal popup.because we have trying to integrate share,view counts,zooming….. through plugin ,so i just want to know that it will run perfectly….. awating for u r reply

  10. Thanks for your response. The website works prefectly in google chrome now.

    However no modal pop-ups in IE 8 or firefox/mozilla.

    Any suggestions why it wont work apart from chrome?

    Thanks in advance.

    Sandeep

  11. Hi,

    I think I am nearly there, but still not able to display the same.

    1. I made the template: ajax-handler.php
    2. I created a page using the template.
    3. I saved the simple modal file (jquery.simplemodal-1.4.js) in my server(with your jquery function appended at the bottom) (the “ajax handler” page permalink “http://www.cygnusfinance.com/?page_id=21”).
    4. I included the jquery.simplemodal-1.4.js file and the http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.jsin my header file.
    5. In my widget i typed: “<a href="” rel=”8″ class=”postpopup”> this link”

    However If you were to click on the link “this link” all i get “ajax handler” modal box; most probably my page title.

    If you can figure out and let me know the problem it will be most helpful.

    Thanks,
    Sandeep

  12. hello, is that possible to handle this popup and giving unique messages for unique links or clicks (without integrating with posts title or whatever) .

  13. @bava Without a link to look at it, it is a bit complex for me to answer. I see you are using jQuery from the jQuery site. Did you replace every instances of “jQuery” by “$” in the your_ajax_function.js file? (see note2 in my post)

  14. Sorry popup link not displaed correct
    here is it
    <a href=“<?php the_permalink() ?>” rel=”postid” class=”postpopup”><?php the_title(); ?>

  15. But it’s not working for me at all.

    let me explain what i did.

    I’ve made
    ajax-handler.php (as template file)
    your_ajax_function.js (link altered)
    jquery-1.4.2.min.js
    simplemodal-1.3.5.min.js

    all .js are added in header file

    and my popup link was <a href="” rel=”postid” class=”postpopup”>

    please anyone help me to work it out.

    thanks in advance.

  16. Hi Kumar, I can see the normal modal box on that page but can’t see any ajax one. You seem to have created the ajax-handler fine and I can see it works so you shouldn’t be far off.

  17. Thanks for your answer!
    It works, I just have to delete the .hide() to.
    But now the posts are displayed one after the other.
    And I don’t know how to test if a post is already loaded…
    Probably something like :
    if (a post is loaded) {
    hide the loaded post and load the new one
    } else {
    load the post
    }
    Any tips?
    Thanks, Terry

  18. Hi Terry, yeah absolutly, I don’t see why not. You can just remove the “.modal()” at the end of the javascript call and the content should be added to your body.

  19. Hey,
    Great article.
    Just one litle question : Is it possible to load the posts in an iframe or a div inside the theme?
    I mean, not in a modal box, but directly in the content.
    Terry.

  20. Hi Grant, I’ve not tried it in multisite mode but I think it could work. You will need to change the way you get the post in the ajax handler though, because in mu mode I think you need to specify which blog you want the post from.

  21. Thank you very much for yet another first-rate article. I am always searching for original WordPress themes to suggest to my readers. Thanks for creating this article. It’s exactly what I was searching for. Truly great post.

  22. Hey,

    Has anyone tried this with WordPress 3.0 MU? Looks like some great code though. I’m going to give it a try now, I have posts on my homepage from several sub blogs and I’d like to be able to pop up an excerpt of the post.

    Grant

  23. Hi Matt, looks like you’ve managed to fix it? What was it in the end? it seems many people are having problems with this tutorial and I would like to make it clearer in some ways so your feedback could help me a lot, thanks.

    Also your javascript seems to call the actual template file when it should call the page using that template file i.e. use the permalink of the page using the ajax-handler template file instead of the path to the file in your theme folder.

    @peter below, I think you are making the same mistake, that would explain why WordPress functions are not working

  24. See the “Privacy Policy” link below the form on the home page: The popup works, but no content from the page loads. I’ve confirmed it is the right page ID, and the template is “ajax handler”. Paths to these files are correct, and js files are all included. Any thoughts on a next step?

  25. After some trial and error I’ve managed to get a WordPress template page to show in the popup box – with the correct post info passed along. However, I cannot get any WordPress functions, such as have_posts(), apply_filters(), query_posts(), to work in the template page. I can’t figure out what I’m doing wrong.

    Fatal error: Call to undefined function have_posts() in /Volumes/iMacWS/ws/wp2/wp-content/themes/linquist/ajax-handler.php on line 9

    I’ve sort of got around it by using mySQL to query wp_posts directly, but would appreciate any advice.

  26. Hi Joanson, adding a ‘overflow:auto’ to the css of the simplemodal box should do the trick.

  27. Hi,
    Who could kindly point out the way how to add vertical and horizontal scrollbars into the simplemodal-container (div) for the case that post content overflows the border of its container? Thanks,

  28. @SPnova If you are using the not minified version of simplemodal you can try replacing all the ‘$’ by ‘jQuery’. But the last time I tried, WordPress was still using jQuery 1.3, which is not compatible with the latest version of SimpleModal I believe.

  29. @vincent 1. Check that you include jQuery and SimpleModal before including the rest of the javascript.

    2. The path to the page seems correct. Have you published a page in WordPress called “Ajax Handler” and is “ajax-handler” the right permalink for that page? Most problems come from people either using a different permalink structure or not publishing the page in the first place.

  30. 2 Firebug errors

    1. $(“”).hide().appendTo(“body”).load(“http://myweb.com/ajax-handler/?id=” + id).modal is not a function

    i have simplemodal and jquery included in header

    And

    GET http://myweb.com/ajax-handler/?id=8 not found

    Having same problem as Pete, but i don’t understand your response.

    1. “The path you want in the load bit is the url to the page created with the ajax handler in WordPress.”

    the path to the page that im calling through ajax? But i thought the re=”id” was going to tell it what to grab.

    load(‘http://urlofyoursite.com/ajax-handler/?id=’+id)

    As i understand the directions this is all that i change “urlofyoursite.com” everything else is the same. THEN the link should just have the rel=”id#”.

  31. @ambit There are a few things to consider here. On the mouseout event you could just do a .hide() to hide the div created with the content. But you should also add a test on your mouseover. If the div with the content already exists then there is not point loading it again. If I put it in words it would say something like: onmouseover, if div exists, modal it, else do ajax request and modal. On mouseout, hide div.

    That will provide you some form of caching so when hovering over elements already loaded, the user will not have to wait for the content to load again, it will display instantly. Hope this makes sense.

  32. Hello there, great post, however, am trying to use it for hover function instead of click. So, for using hover, two fucntions need to be written in jquery, one for mosueover and one for mouseout, so, my question is, what to write in the mouseout fucntion?

  33. Thank you very much, everything works now! Your tip about using the permalink and also incluing the right parameter (in my case it was not ‘id’ but ‘page_id’) fixed everything.

  34. Hi Pete,

    The snippet means something like: create div with id ‘ajax popup’, hide it (display: none) then add it to the code of the body (at the end), then load the content of the page into it and apply the modal function to the lot.

    The path you want in the load bit is the url to the page created with the ajax handler in WordPress. So no wp-content/themes/simpleBlog… When you create the page in WordPress you should see the permalink just below the title input field. That’s the url you want in there. Hope this helps.

  35. Hi, I’ve been struggling to get this to work for a couple of days without success. I Installed jQuery and SimpleModal and also inserted that javascript snippet in the header. I have created a page which uses the ajax-handler.php template.

    I’m pretty new to AJAX, so I’m having a hard time understanding the following code in the snippet:

    jQuery(”).hide().appendTo(‘body’).load(‘http://mywebsite.com/wp-content/themes/SimpleBlog/ajax-handler/?id=’+id).modal();

    First of all, must I include the complete path of the theme I’m using after mywebsite.com? And what about ‘ajax-handler’, to me it looks like a directory on the server that in reality doesn’t exist. Or is that some kind of a virtual directory / function that jQuery creates / uses?

    Anyway, Firebug says that:

    GET http://mywebsite.com/wp-content/themes/SimpleBlog/ajax-handler/?id=4 404 Not Found

    (4 is the page ID, and that page exists)

    I’m confused… I do code quite a lot, but this AJAX stuff is new to me. Please help!

  36. great example! How about you add an animated gif background in css on the div#ajax-popup and add a background color to your div.rider-bio so when it is loaded it will mask the loading animation?

    A better solution would be to add the gif as an image using javascript and hide it when the content as been load but you’ll need the uncompressed version of simple modal to see where the code needs to go.

  37. @james Yes that’s possible. It is only up to you how you style the popup. Pretty neat example I have to say, thanks for sharing.

  38. @David Not too sure about what you mean with the popups.php? Or is it popups.js? Anyway, I would recommend checking in Firebug what’s going on or email me a link at admin@thisdomainname.

  39. Likewise, this isn’t working for me and I cannot work out what’s going wrong.

    I have the Ajax Handler page saved, using the ajax-handler.php file as template. header.php is calling http://{mywebserver}/{theme}/js/popups.php file that has your jquery function and SimpleModal in it.

    jQuery is being called like this:
    http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/

    Then this is the link I’m using:

    The post ID is correct, the functions are identical to yours, the files are all in the right places and have the right names, the link to popups.php is pointing to the correct location, but the class=”postpopup” link does nothing whatsoever. I’ve disabled all other plugins to make sure nothing is conflicting too.

  40. The only thing I can think of when I look at the steps you followed is that you haven’t called the two javascript files as well as jQuery in your template header. You have to specificly load them otherwise they wont get included on the page.

    If you look at the source code of the this page you should see right at the bottom (line 399) where I call the gallery.js file, which holds the ajax function and SimpleModal.

  41. Hi, I added another post since you posted this answer (see above). I’ve gone through all the steps as best I can, but it’s still not working. Can you look at what I’ve done (listed above step by step) and see if you can spot the error? Thanks for your help!

  42. I’m having trouble getting this to work. I am on WP 2.8.6. Here is what I did:

    1. Created a page template called ajax-handler.php with the code you provided in your first code box, plus this code – . I’ve tried placing this just under the php template designation section, and also tried it within the loop. Uploaded it to the theme root.

    2. Uploaded the jquery.simplemodal-1.3.3.min.js file into my theme js folder.

    3. Created a js file containing the jquery function from your second code box (with my url corrected) and uploaded it into the theme js folder.

    4. Created a link as follows – Subscribe

    When I click on the link, it just takes me to the new page in the usual way. No pop up.

    Can you tell me what I’m doing wrong? Thanks so much for your help!

  43. To answer your first comment, yes I believe it would work with any kind of content but I haven’t tested it with anything else than normal post. I have updated the post so it should be clearer where the javascript function go (see the “note” section below the code).

    Hope this helps.

  44. I haven’t worked with jQuery and SimpleModal before. Everything seems pretty self-explanatory except for the function you show.

    Where do I put that?

  45. Hey, this looks awesome and it may be just what I was looking for. Tell me, can the pop up box be interactive – for instance, could I have my subscription form in there and have it be usable? Or will it only work with static content?

Leave a Reply

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