Magento 2 / WordPress Integration Custom Post Lists

First Published: December 14, 2016

A great way to further the integration of your Magento and WordPress applications is to place lists of posts that update 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 1 Template File

<?php $posts = Mage::getResourceModel('wordpress/post_collection')
  ->load(); ?>
<?php if (count($posts) > 0): ?>
    <?php foreach($posts as $post): ?>
        <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 $image->getAvailableImage() ?>" src="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" />
        <?php endif; ?>
        <p><?php echo $post->getPostExcerpt(40) ?></p>
    <?php endforeach; ?>
<?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.

The above is a basic post list but you can do much more. For more information please see the Magento WordPress Integration code examples article.