I tried to do a ajax call in my wordpress loop, basically i would like to load the content of the post in the home page in a div, after the click on the title.
the call ajax seems work, but i have the problem that load whole the page, and i would like to load only the content of a div with specific id.
this is my code: index.php
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a class="post-link" rel="<?php the_ID(); ?>" href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php endwhile; endif; ?>
<div id="single-post-container"></div>
this is the single.php
<?php $post = get_post($_POST['id']); ?>
<div id="single-post post-<?php the_ID(); ?>">
<?php while (have_posts()) : the_post(); ?>
<?php the_title();?>
<?php the_content();?>
<?php endwhile;?>
</div>
and this is the js
jQuery(document).ready(function(){
jQuery.ajaxSetup({cache:false});
jQuery(".post-link").click(function(){
var post_link = jQuery(this).attr("href");
jQuery("#single-post-container").html("content loading");
jQuery("#single-post-container").load(post_link);
return false;
});
});
i tried to add the id #single-post after post_link like this:
jQuery("#single-post-container").load(post_link #single-post);
but when i run gulp i have an error that block me.
how can i achieve this scope?
someone could give me an help or suggestion?
I think this may be the answer but only if I have correctly understood the problem:
What is post_link? What actual url is your AJAX call calling? If you are just calling single.php the first thing that does is call header() – hence you might get the whole page. Looking at your index.php i think this may be what is happening.
If so. You need to look up how to do AJAX calls in WordPress. You have to add an AJAX callback with something like add_action(‘wp_ajax_my_action’, mycallback). Then your callback can just get the single post with get_post(). The actual url your AJAX call should be calling is something like:
yourdomain/wp-admin/admin-ajax.php?action=my_action&post_id=THEPOSTID. You can use admin_url() to help you build the correct url.
You may need to inject THEPOSTID into your JavaScript. Using wp_localize_script. Or you could add it as an attribute in index.php and get it in your JavaScript.
Then your callback – mycallback() – can use get_post() to get just the post and return it without all the page fluff. E.g.:
Maybe look for a few examples on how to do AJAX with WordPress? e.g. http://wptheming.com/2013/07/simple-ajax-example/
UPDATE:
added wp_die(); at the end of the AJAX call-back. You need to do this to stop WordPress spitting out a lot of page bumf as well. In fact this may be the part that is missing from your single.php. Stil, probably better to do to it using admin-ajax.php anyway perhaps.
if this can help someone, i solved with this code
thanks you all anyway