Listing WordPress Posts

So you have a WordPress site that hosts your blog posts along with a regular site and you want to list the blog posts on the other site, dynamically without having to manually add to the list every time you post something new. Here’s how I accomplished it.

Disclaimer: I found some of this on another site, but forgot where, so apologies for not giving credit where credit is due.

Create a posts.php page at the root of your WordPress site with the following:

<?php require('wp-blog-header.php');
<h4>::~ChrEli-BLOG~:: Posts</h4>
$args = array( 'numberposts' => 100, 'category' => 0, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
$posts = get_posts( $args );

 foreach ($posts as $post) :  setup_postdata($post); ?>
        <td><a href="<?php the_permalink(); ?>" title="<?php the_title();?>" target="_blank"> <?php the_title(); ?></a></td>
        <td><?php the_date(); ?></td>
<?php endforeach; ?>

The above will produce an un-stylized output like the following:

To integrate with your other website, perform the following:

In the <head> element, add the following:

        $( "#posts" ).load( "<LINK_TO_POSTS_PHP>", function(response, status, xhr){
            if (status == "error") {
                alert(msg + xhr.status + " " + xhr.statusText);

Where <LINK_TO_POSTS_PHP> is the fully qualified link to the posts.php you created earlier.

Next, create a <div> element with the id of “posts”.

<div id="posts"><div>

If your sites are in different domains, you may get a message similar to the following in the JavaScript console:

XMLHttpRequest cannot load http://<BLOG_SITE_DOMAIN>/posts.php. No 
'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://<SITE_ON_DIFFERENT_DOMAIN>' is therefore not allowed access.

Where <BLOG_SITE_DOMAIN> is the site for your WordPress blog and <SITE_ON_DIFFERENT_DOMAIN> is the site you trying to call http://<BLOG_SITE_DOMAIN>/posts.php from.

The reason for this is it is seen a a XSS (cross-site-scripting) attack. To work-around the above, add the following to the beginning of posts.php:

<?php header('Access-Control-Allow-Origin: http://<SITE_ON_DIFFERENT_DOMAIN>'); ?>

Whatever you do, DO NOT put * where http://<SITE_ON_DIFFERENT_DOMAIN> is.; that’s just asking for trouble.

The end result should look as follows:

And that’s all I have to say about that.

This entry was posted in Geek, PHP, WordPress and tagged , , , . Bookmark the permalink.

Leave a Reply