I'm loading posts via Ajax into a div that I have set up on index page.

index page loop:

 <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
       <button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
       <?php the_post_thumbnail(); ?>
       <a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title(); ?></a>
<?php endwhile; endif; ?>


<div id="post-container"></div>



        var post_link = $(this);

    return false;


How to add posts into div with ajax and assign them specific post format?

  • can you give action callback codes you used for this ajax request? Jan 19 '17 at 9:15

First of all you need to register a action callback for you ajax request.
Secondly you need to send all ajax request to wp-admin/admin-ajax.php (both GET and POST).
And lastly you need to modify your javascript a little to pass the action parameter which will trigger the callback. and var post_link = $(this); doesn't gives the post id from rel attribute you should use var post_link = $(this).attr("rel");

You can get the ajax url by admin_url( 'admin-ajax.php' ); in your theme. and use javascript localization to get inside your js.

Everything else looks good on your index.php



        var post_id = $(this).attr("rel");
        // update: .load() should send request to ajax url not the post url
    return false;

PHP (in your theme's function.php)

add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );
add_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );

function load_more_post_callback() {
    if( isset($_GET["pid"]) ){
        $post = get_post( $_GET["pid"] );
        if( $post instanceof WP_Post ) {
            echo '<h1 class="post_title">'.$post->post_title.'</h1>';
        } else {
            // nothing found with the post id
    } else {
        // no post id
  • post are not loading in div please check TEST-LINK
    – FRQ6692
    Jan 19 '17 at 15:01
  • i also want to use this for CPT and Max to load in post = 4, please adjust php.. Thanks
    – FRQ6692
    Jan 19 '17 at 15:03
  • your post_link is not defined; and as your test-link showing your using inline javascript in footer please change $("#post-container").load(post_link+"?action=load_more_post&pid="+post_id); with $("#post-container").load("<?php echo admin_url( 'admin-ajax.php' ); ?>?action=load_more_post&pid="+post_id);. and if you want to put this snippet in separate file please use javascript localization. see the answer. Jan 19 '17 at 17:31
  • How to load title+thumbnail, unable to load thumbnail.
    – FRQ6692
    Jan 20 '17 at 7:18

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.