WordPress Quick-tip: Display x number of posts outside your blog.
Sometimes, you may want to display posts outside of WordPress. Here are a few resources that helped.
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 following 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 WP_Query function, you can target the number of days to show. The codex includes the following example:
$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')) . "'";
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();
echo '<li>' . get_the_title() . '</li>';
}
Unfortunately, the number of posts returned seemed to be a bit off. To fix it, I used the idea in the following post (StackOverflow: Display posts newer than 30 days) to add -1 to my argument. With that change, your code should look more like this:
//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');
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')) . "'";
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>';
}
}
?>