Skip to main content

WordPress Quick-tip: Display x number of posts outside your blog.

Sometime, you want to display posts outside of WordPress. Here are some resources to help.

From the Integrating WordPress in your Website codex file, the first place you start is to include a WordPress header file:

<?php
define('WP_USE_THEMES', false);
require('/the/path/to/your/wp-blog-header.php'); //found in the root of your WordPress install.
?>;

If you are using a multi-site blog, you will also need to add the below under the require:

switch_to_blog($blogID);

From the codex, the quickest example of showing a post is the following code:

$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
foreach ($posts as $post) : start_wp();
the_date(); echo "<br>";
the_title();
the_excerpt

Using the WPQuery function, you can target the number of days to show. The codex has the example code:

$args = array(
    'post_status' => 'publish'
);
function filter_where( $where = '' ) {
	// posts in the last 30 days
	$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; //change 30 to the number of days you want
	return $where;
}<br>
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $args );
remove_filter( 'posts_where', 'filter_where' );

while ($query->have_posts()) {
   $the_query->the_post();
   echo '<li>' . get_the_title() . '</li>';
}

Unfortunately, the number seemed to bit off. To fit it, I used the idea in the following post (StackOverflow: Display posts newer than 30 days) to add in my argument, -1. Now, your same code should be similar to below:

//update args with:
$args = array(
    'posts_per_page' => -1,
     'post_status' => 'publish'
);

Full source code:

<?php
define('WP_USE_THEMES', false);
require('/the/path/to/your/wp-blog-header.php'); //found in the root of your WordPress install.
switch_to_blog($blogID);

$args = array(
    'posts_per_page' => -1,
     'post_status' => 'publish'
);
function filter_where( $where = '' ) {
	$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; //change 30 to the number of days you want
	return $where;
}
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $args );
remove_filter( 'posts_where', 'filter_where' );

while ($query->have_posts()) {
   $the_query->the_post();
   if (get_the_title()<>''){
        echo '<li>' . get_the_title() . '</li>';
   }
}
?>;