Skip to main content
3 of 6
added 29 characters in body
Johansson
  • 15.4k
  • 11
  • 43
  • 79

Short answer: DON'T DO IT! Even if yesterday you said tomorrow!

Including WordPress's core in some other files is the last thing you want to do. Instead, use an Ajax method and fill the content by using a REST endpoint.

You need to register a rest route first. To do so, add this piece of code into your theme's functions.php:

add_action( 'rest_api_init', function () {
    register_rest_route( 'vinay', '/ajax_blog/', array(
            'methods' => 'GET', 
            'callback' => 'blog_ajax_function' 
    ) );
});

Now, you can do your query inside a callback function:

function blog_ajax_function(){
    $recent_posts = wp_get_recent_posts( $args, OBJECT );
    foreach ( $recent_posts as $post ) {
        $data[]['title'] = get_the_title( $post->ID );
        $data[]['date'] = get_the_date( 'Y-m-d H:i:s', $post->ID );
        $data[]['permalink'] = get_the_permalink( $post->ID );
        $data[]['thumbnail'] = get_the_post_thumbnail_url( $post->ID );
    }
    return $data;
}

Now, you can get a JSON response containing title, date and thumbnail of your recent posts by visiting wp-json/vinay/ajax_blog/. Time to add them to our page.

Let's bind an action to page load and fill the page with fancy bubbly posts, just like spongebob did!

<script>
(function(){
    $.ajax({
        type: 'GET', 
        url: 'http://example.com/wp-json/vinay/ajax_blog', 
        dataType: 'json',
        success: function (data) {
            if (data != null) {
                $.each(data, function(index, element) {
                    $('#container-div').append('<a href="'+element.permalink+'"><img src="'+element.thumbnail+'" alt="'+element.title+'"/><span>'+element.title+'</span>' +element.date+ '</a>');
                });
            }
        }
    });
})(jQuery);
</script>

This will append a list of clickable recent posts to the <div id="container-div"></div> that we create in our HTMl to contain the posts.

All done.

Johansson
  • 15.4k
  • 11
  • 43
  • 79