Displaying Recent WordPress Posts in Magento
A great way to further the integration of your Magento and WordPress applications is to place lists of posts that updated dynamically throughout your site. This could be a general list of the most recent posts in your footer or posts tagged with a specific tag on a category page. Adding this extra layer of integration allows you to position useful content around your site.
Adding Recent Blog Posts to a Magento Template File
<?php $posts = Mage::getResourceModel('wordpress/post_collection') ->addPostTypeFilter('post') ->setOrderByPostDate() ->addIsViewableFilter() ->setPageSize(5) ->load(); ?> <?php if (count($posts) > 0): ?> <ul> <?php foreach($posts as $post): ?> <li> <a href="<?php echo $post->getPermalink() ?>"><?php echo $this->escapeHtml($post->getPostTitle()) ?></a> <?php if ($image = $post->getFeaturedImage()): ?> <a href="<?php echo $post->getPermalink() ?>"> <img src="<?php echo $post->getAvailableImage() ?>" src="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" /> </a> <?php endif; ?> <p><?php echo $post->getPostExcerpt(40) ?></p></li> <?php endforeach; ?> </ul> <?php endif; ?>
The code above will generate a collection of your 5 most recent blog posts and loop through them and display them.
If you want to change the post type, you can either pass a different post type to addPostTypeFilter, an array of post types or a '*' value, which means include all post types. You can also change the number from 5 to any number and this will limit the number of posts displayed. You can remove this line completely (or set it 0) to include all posts.
Here are a few more filters you can apply to the $posts collection to get more specific posts.
<?php /* Filter by category IDs */ ?> <?php $posts->addCategoryIdFilter(array(1, 2)) ?> <?php /* Filter by a post author ID */ ?> <?php $posts->addFieldToFilter('post_author', $4) ?> <?php /* Filter by a tag */ ?> <?php $posts->addTermFilter('mytag, 'post_tag', 'name') ?>
By using a combination of these filters, you can specify exactly the posts that you want to see in the results. You can also customise the HTML and apply any CSS that you like to get your posts looking exactly how you want them.
You can also customise how the image works. For more information on this, please see the images in Magento WordPress Integration article.
For more information on filters, see the Advanced Coding in Magento WordPress Integration article.