Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

load posts without reload (ajax) WordPress

  • SOLVED

looking for a snippet that will load posts via jquery without reloading the page. so if you click on a category link aka /category/news it will reload showing a post listing without reloading the whole page.

Answers (10)

2010-08-29

Khanh Cao answers:

First you need to declare a function to load posts:


// ajax: generate a list of posts from a list of post types
function my_get_posts()
{
//permission_check(); <-- check nonce and permissions here

// show only published posts
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'nopaging' => true, // show all posts in one go
);

$posts = get_posts($args);

// put the posts into an array
$arr = array();
foreach ($posts as $post)
{
$entry = array();

// get the post's attributes here
$entry['id'] = $post->ID;
$entry['title'] = $post->post_title;
$arr[] = $entry;

}

// then output in json format
header("Content-Type: application/json");
echo json_encode($arr);

// make sure you have "exit" here
exit;
}

// add into the ajax action chains

// this is for logged in users
add_action('wp_ajax_my_get_posts', 'my_get_posts');

// this is for the rest
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts');


Now the jquery snippet:


jQuery.ajax({
type: 'POST',
url: 'http://domain.com/wp-admin/admin-ajax.php',
data: {
action: 'my_get_posts' // this must be the same with your ajax function name
},
success: function(data, textStatus, XMLHttpRequest)
{
for (var entry in data)
{
// get post's attributes
var postID = data[entry].id;
var title = data[entry].title;

// append new post into some list
$("#some-list").append("<li>" + title + "</li>");

}
},
error: function(MLHttpRequest, textStatus, errorThrown)
{
},
complete: function(XMLHttpRequest, textStatus)
{
},
dataType: 'json'
});



Note: Firebug may eat the ajax results if you have its panel active, so better close it if you're not debugging


chrismccoy comments:

im looking for something along these lines

http://winysky.com/

the 4 links below the slider, click on WP and you will see the result


Khanh Cao comments:

I guess each of the links is a category so for example for we 4 links:

<ul>
<li id="col1"><a href="#">Category 1</a></li>
<li id="col2"><a href="#">Category 2</a></li>
<li id="col3"><a href="#">Category 3</a></li>
<li id="col4"><a href="#">Category 4</a></li>
</ul>


Change the load posts function to:

// ajax: generate a list of posts from a list of post types
function my_get_posts()
{
//permission_check(); <-- check nonce and permissions here

// get the category ID we need to load from
$cat_id = $_POST['cat'];

// show only published posts
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'nopaging' => true, // show all posts in one go
'cat' => $cat_id // load only from this category
);

$posts = get_posts($args);

// put the posts into an array
$arr = array();
foreach ($posts as $post)
{
$entry = array();

// get the post's attributes here
$entry['id'] = $post->ID;
$entry['title'] = $post->post_title;
$entry['link'] = get_permalink($post->ID);
$arr[] = $entry;

}

// then output in json format
header("Content-Type: application/json");
echo json_encode($arr);

// make sure you have "exit" here
exit;
}

// add into the ajax action chains

// this is for logged in users
add_action('wp_ajax_my_get_posts', 'my_get_posts');

// this is for the rest
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts');


Now, supposed the element where we need to show the posts is <ul id="the-posts"></ul>, set the links' click events like this:


function loadPostsFromCat(category)
{
// clear the-posts content
jQuery("#the-posts").children().remove();

// show the loading image here
// showWaitingImage();

jQuery.ajax({
type: 'POST',
url: 'http://domain.com/wp-admin/admin-ajax.php',
data: {
'action': 'my_get_posts' // this must be the same with your ajax function name
'cat': category
},
success: function(data, textStatus, XMLHttpRequest)
{
for (var entry in data)
{
// get post's attributes
var title = data[entry].title;
var link = data[entry].link;

// append new post into the-posts, with permalink
jQuery("#the-posts").append("<li><a href='" + link + "'>" + title + "</a></li>");

}
},
error: function(MLHttpRequest, textStatus, errorThrown)
{
},
complete: function(XMLHttpRequest, textStatus)
{
// hide the loading image
// hideWaitingImage();
},
dataType: 'json'
});
}

// set the links' events, you may do a for loop here
jQuery("#col1 a").click(function(event)
{
loadPostsFromCat(1); // load from the category with ID of 1
event.preventDefault();
return true;
});

// do the same with other links but change the cat ID



The trick here is to tweak get_posts() to load what you wish to. If you don't like to use category IDs, you can use category slugs by changing 'cat' => $cat_id to 'category_name' => $cat_id and change $cat_id to something that makes more sense :-)


chrismccoy comments:

i get an error with the jquery code.

} expected at line 14

2010-08-29

John Farrow answers:

try this great screencast

http://css-tricks.com/video-screencasts/81-ajaxing-a-wordpress-theme

2010-08-29

Monster Coder answers:

[[LINK href="http://ajaxedwp.com/"]]You need this one![[/LINK]]


chrismccoy comments:

i have used that one, its not what i am looking for, its too bloated, just looking for a simple way without a plugin.


Monster Coder comments:

you can load parts of page using AJAX by using jQuery's load() api!

suppose, a link is like this:

<div id="container">

<a href="LINK_TO_CATEGORY">Category</a>
</div>


you can write jquery to load the category page using ajax, something like below (for idea only):
jQuery('a').click( function(){
var target = jQuery(this).attr('href');
jQuery('#container').load(target+' #container');
});


You can check the following link:
http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html

2010-08-29

Utkarsh Kukreti answers:

If you're familiar with php, this should be straightforward - http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html

2010-08-29

Rashad Aliyev answers:


That's simple way..

Open this URL! [[LINK href="http://www.emanueleferonato.com/2010/04/01/loading-wordpress-posts-with-ajax-and-jquery/"]]http://www.emanueleferonato.com/2010/04/01/loading-wordpress-posts-with-ajax-and-jquery/[[/LINK]]

2010-08-29

Tobias Nyholm answers:

As a seo expert, I have to say: "That is suicide". Google will have big problems reading your page content if you load it with ajax.

2010-08-29

Deepak Thomas answers:

<blockquote>
Tobias Nyholm says:

As a seo expert, I have to say: "That is suicide". Google will have big problems reading your page content if you load it with ajax. </blockquote>

This wont be a problem if you are using some additional JS like jQuery for ajaxifying (the basic functionality remains intact even w/o it). Search Engines being JS unaware will render it normally.

The best way to ajaxify your theme would be to follow this sceencast
http://css-tricks.com/video-screencasts/81-ajaxing-a-wordpress-theme/
You can see a DEMO of how it'd be here:
http://themeplayground.digwp.com/index.php?wptheme=All%20AJAX

2010-08-30

Nilesh shiragave answers:

if you are developer then its easy just see

http://css-tricks.com/video-screencasts/81-ajaxing-a-wordpress-theme

http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html

2010-08-30

Ehthisham tk answers:

It is easy when you are using a plugin.
http://www.emanueleferonato.com/2010/04/01/loading-wordpress-posts-with-ajax-and-jquery/

2010-08-31

Kalees Thavamani answers:

After seeing how to include jQuery Ajax calls in your WordPress blog, it’s time to load posts on the fly, without reloading the page.
As for the previous example I am using the standard Kubrick theme… without any plugin installed.
Look how I load the posts under the header by clicking on their titles… even the ones with “more” tag appear complete without reloading the page:

<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/_q7tKTn_z9s?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/_q7tKTn_z9s?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>

Let’s start with header.php modifications
This is the script I added under
<?php wp_head(); ?>
That is the JQuery part
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({cache:false});
$("h2 a").click(function(){
var post_id = $(this).attr("rel")
$("#your_post_here").html("loading...");
$("#your_post_here").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/triqui-ajax/",{id:post_id});
return false;
});
});
</script>
I already explained the first 4 lines in the previous tutorial.
Line 5: Waiting for the user to click on an hypertext over an h2 heading. I am doing it because in Kubrick post titles are rendered this way:
<h2><a href="<?php the_permalink() ?>"....
This should change from theme to theme, but this works on Kubrick
Line 6: Retrieving the rel attribute of the link and saving it in a variable called post_id. You’ll see later in this tutorial how this attribute will contain the unique ID of the post we want to show.
Line 7: In an element with your_post_here id I am writing “loading…” because I’m starting to load the post. You’ll see later in this tutorial where to place the element
Line 8: Now thw ajax magic… in the your_post_here element this time I load the output of a page of the blog called triqui-ajax. You’ll se later in this tutorial how to create it. This will work if the permalinks of your blog aren’t the default ones. Go to Settings -> Permalinks and select Day and name

I am also passing in POST a variable called id with the content of post_id variable (the post unique id)
Line 9: I added this line to prevent the browser to jump to the link… remember? I want to load the post in the same page.
Now it’s time to make some changes to index.php
This is how I modified it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
/**
* @package WordPress
* @subpackage Default_Theme
*/

get_header(); ?>

<div id="content" class="narrowcolumn" role="main">
<div id = "your_post_here"></div>
<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h2><a href="<?php the_permalink() ?>" rel="<?php the_ID(); ?>" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<div class="entry">
<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>

<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></p>
</div>

<?php endwhile; ?>

<div class="navigation">
<div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
</div>

<?php else : ?>

<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php get_search_form(); ?>

<?php endif; ?>

</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>
To tell the truth, I only added a line and changed a bit another one:
Line 10: This is the div that will contain the post, the one I change with jQuery (remember? lines 7 and 8 in the jQuery script)
Line 16: Here I changed the rel attribute to store the unique id of the post I want to load. I used it at line 6 in the jQuery script
And the template files do not need any other change.
Now it’s time to create a new page template with some code that will load the selected post.
In your template directory create a new php file, no matter its name… you can call it example.php and write this:
<?php
/*
Template Name: Triqui Ajax Post
*/
?>
<?php
$post = get_post($_POST['id']);
?>
<?php if ($post) : ?>
<?php setup_postdata($post); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<div class="entry">
<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>

<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></p>
</div>
<?php endif; ?>
As you can see it’s almost the same code you can find in index.php at lines 15-24… because I just want to load a post in the same way the index file does. I just removed the anchor tag in the title, because I don’t want it to be clickable. And obviously I read the id value passed by the jQuery script at line 8
The only interesting lines are lines 2-4… yes, the comment… because this way I am giving the template page the name Triqui Ajax Post.
Now in your admin area create a new page, call it Triqui Ajax (do you remember the permalink url at line 8 in the jQuery script…) and select Triqui Ajax Post as template

And that’s it… you don’t need anything else, and the blog will work as in the video.