This Article is about How to load wordpress posts with featured images in PHP script and of course AJAX.
This task requires a bit basic skills with PHP and Javascript.
I will show you a small snippet of code how to load WordPress functions in your external PHP script. I used this snippet to load blog posts via AJAX on static HTML page with jQuery.
There are few simple steps:
1. Load wp-load.php to have all WordPress functions available in your PHP script.
2. Create a loop to show post with featured image
3. Output the loop to browser (send via AJAX)
My advice for developers that try to use the_content(), the_permalink(), the_post_thumbnail() and etc. Use them if you want to show the loop in this file. If you send data over AJAX with variables/arrays use get_the_content(), get_the_permalink(), get_the_post_thumbnail().
Load posts outside of the WordPress – [example snippet]
[php]
<?php
// Loads the WordPress Environment
if ( !isset($wp_did_header) ) {
$wp_did_header = true;
// Load WordPress functions
require_once(‘blog/wp-load.php’);
wp();
require_once( ABSPATH . WPINC . ‘/template-loader.php’ );
global $posts;
global $wp;
global $wpdb;
// How many post you want to show
query_posts(‘showposts=5’);
// Variable that will return result to AJAX request
$return[‘posts’] = ”;
}
// WordPress loop start
if (have_posts()) : while (have_posts()) : the_post();
$return[‘posts’] .=’
<div class="blog_item">
<div class="imageContainer">’. get_the_post_thumbnail($post->ID, array(200,160) ) .'</div>
<h2>’. get_the_title($post->ID) .'</h2>
‘. get_the_content($post->ID). ‘
<a href="’. get_permalink($post->ID) .’">Read more</a>
</div>’;
// WordPress loop end
endwhile; endif;
// Cleaning the worpdress queue
wp_reset_query();
// Encode and return result to AJAX request
echo json_encode($return);
?>;
[/php]