How to load post content on index page using ajax when post title in sidebar is clicked

You will need to create a WordPress function that loads the post content and hook that into wp_ajax_nopriv. You will also need the jQuery ajax functions to send the $_POST data to your WordPress function via ajax and output the returned content in your empty div where you want it to display.

A simple approach would be to use the post ID in the class or id div tag so you can easily pull it out with jQuery.

Example using the sidebar code from Steven’s answer:

 echo '<ul id="sidebar-ajax">';
  foreach($sidebar_posts as $post):
    echo '<li id="' .get_the_ID(). '">';
    echo '<a class="ajax-click" href="#">.'get_the_title().'</a>';
    the_title('<h3>','</h3>');
    echo '</li>';
  endforeach;
  echo '</ul>';

Example jQuery (this should be in a separate file and enqueued using wp_enqueue_script so the the ajax url can be defined as a javascript namespace variable using wp_localize_script:

Enqueue the script and set the ajax url variable:

wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

Contents of the ajax.js file:

    jQuery(document).ready(function($) {

        $(".ajax-click").click(function() {
            $("#loading-animation").show();
            var post_id = $(this).parent("li").attr("id");
            var ajaxURL = MyAjax.ajaxurl;

            $.ajax({
            type: 'POST',
            url: ajaxURL,
            data: {"action": "load-content", post_id: post_id },
            success: function(response) {
                $("#empty_div_in_content").html(response);
                $("#loading-animation").hide();
            return false;
        }
    });    
   });
)};

*Note: Add a loading animation graphic where the post will eventually display and and give it a div id of “loading-animation” and set it to display: none.

WordPress function to return the post content to the ajax call:

add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
    function my_load_ajax_content () {
        $post_id = $_POST[ 'post_id' ];
     
        $post = get_post( $post_id, OBJECT);
        $response = apply_filters( 'the_content', $post->post_content );
  
        echo $response;
        die(1);
    }

Leave a Comment